package com.goldcn.goods.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.goldcn.b2b.service.ClassifyDiscountService;
import com.goldcn.cart.dao.GoodsCartMapper;
import com.goldcn.common.CommonTools;
import com.goldcn.common.DataUtils;
import com.goldcn.common.HttpUtil;
import com.goldcn.common.JsonUtil;
import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.model.DataResult;
import com.goldcn.common.util.CommonUtils;
import com.goldcn.common.util.IdGen;
import com.goldcn.config.ProConstants;
import com.goldcn.enumeration.CfgExtEnum;
import com.goldcn.enumeration.ErrorCodeEnum;
import com.goldcn.enumeration.GoodsStateEnum;
import com.goldcn.enumeration.OperateTypeEnum;
import com.goldcn.goods.dao.*;
import com.goldcn.goods.dto.*;
import com.goldcn.goods.model.*;
import com.goldcn.goods.vo.*;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.order.dto.UserIDGoodsByDto;
import com.goldcn.order.dto.UserInfoForOrderDto;
import com.goldcn.order.service.CommissionUserService;
import com.goldcn.order.service.OrderService;
import com.goldcn.order.service.RebateService;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import net.sf.json.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Administrator on 2016/11/14.
 */
@Service
@ConfigurationProperties("bank")
@Component
public class GoodsService {

    @Autowired
    private GoodsImagesMapper goodsImagesMapper;
    @Autowired
    private GoodsSkuMapper goodsSkuMapper;
    @Autowired
    private GoodsInfoMapper goodsInfoMapper;
    @Autowired
    private GoodsCartMapper goodsCartMapper;

    @Autowired
    private ClassifyShopMapper classifyShopMapper;

    @Autowired
    private ClassifyTagMapper classifyTagMapper;

    @Autowired
    private GoodsTagMapper goodsTagMapper;


    private Logger logger = Logger.getLogger(GoodsService.class);
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    RestTemplate rest;

    @Autowired
    GoodsIndexService goodsIndexService;

    @Autowired
    OrderService orderService;

    @Autowired
    GoodsClassifyCommissionService goodsClassifyCommissionService;
    @Autowired
    GoodsLabelService goodsLabelService;
    @Autowired
    CommissionUserService commissionUserService;
    @Autowired
    RebateService rebateService;

    @Autowired
    GoodsShopMapper goodsShopMapper;

    @Autowired
    GoodsSkuShopMapper goodsSkuShopMapper;

    @Autowired
    ClassifyDiscountService classifyDiscountService;

    @Autowired
    GoodsAttrStoneMapper goodsAttrStoneMapper;

    public Integer indexMove() {
        Integer pageNum = 0;
        Integer pageSize = 99;
        Integer pages = 1;

        //查询所有的在售中商品
        QueryGoodsDto queryGoodsDto = new QueryGoodsDto();
        queryGoodsDto.setIsAudit(1);

        while (pages > pageNum) {
            PageHelper.startPage(pageNum++, pageSize, "info.addTime desc");//分页初始化

            Page page = (Page) goodsInfoMapper.selectCondition(queryGoodsDto);
            pages = page.getPages();
            int index = 0;
            for (QueryResultGoodsDto goods : (List<QueryResultGoodsDto>) page.getResult()) {
                logger.info(pageNum + "@@@@@@" + (++index));
                goodsIndexService.addIndexing(goods.getGoodsID());
            }
        }
        return pageNum * pageSize;
    }

    public boolean initAllIndex() {
        List<Long> goodsIDs = goodsInfoMapper.selectAll(SystemContext.getCompanyID(), 1);
        for (Long goodsID : goodsIDs) {
            boolean result = goodsIndexService.addIndexing(goodsID);
            if (!result) {
                throw new ServiceException("添加索引失败", RestConst.ErrorCode.SERVICE_FAIL);
            }
        }
        return true;
    }

    public boolean indexDelete() {
        List<Long> goodsIDs = goodsInfoMapper.selectAll(SystemContext.getCompanyID(), 1);
        for (Long goodsID : goodsIDs) {
            boolean result = goodsIndexService.deleteIndexing(goodsID);
            if (!result) {
                throw new ServiceException("删除索引失败", RestConst.ErrorCode.SERVICE_FAIL);
            }
        }
        return true;
    }

    /**
     * 操作商品 新增or编辑
     *
     * @param goodsDetailsVo
     * @return
     */
    @Transactional
    public Long operateGoods(GoodsDetailsVo goodsDetailsVo) {
        try {
            GoodsInfoWithBLOBs gi = new GoodsInfoWithBLOBs();
            Long time = CommonUtils.getCurTimestamp();
            BeanUtils.copyProperties(goodsDetailsVo.getGoodsInfoVo(), gi);
            switch (goodsDetailsVo.getOperateType()) {
                case insert:
                    gi.setGoodsID(IdGen.get().nextId());   //给新建商品一个ID
                    gi.setAddTime(time);
                    gi.setAddUser(goodsDetailsVo.getGoodsInfoVo().getOpreateUser());
                    gi.setOnsale(0);//上架
                    gi.setIsAudit(0);//未审核
                    break;
                case update:
                    gi.setIsAudit(0);//未审核
                    gi.setUpdateUser(goodsDetailsVo.getGoodsInfoVo().getOpreateUser());
                    //通知购物车中该商品失效
                    this.notifyGoodsCartExpire(gi.getGoodsID(), 0);
                    this.notifyShopGoodsExpire(gi.getGoodsID(), null);
                    break;
            }
            gi.setUpdateTime(time);
            //checkGoodsPrice(gi,goodsDetailsVo.getGoodsSkuList());
            // 1.保存图片到图片表
            batchInsertGoodsImages(gi, goodsDetailsVo.getImageUrlList());

            // 2.保存规格(sku)到sku表
            batchInsertGoodsSkuInfo(gi, goodsDetailsVo.getGoodsSkuList(), goodsDetailsVo.getOperateType());

            // 3.保存标签信息/分组作息
            batchInsertGoodsTags(gi, goodsDetailsVo.getTagList());

            //4.插入主表信息
            operateGoodsInfo(gi, goodsDetailsVo.getOperateType());

            return gi.getGoodsID();
        } catch (ServiceException se) {
            throw se;
        } catch (Exception e) {
            logger.info(e.getMessage());
            throw CommonTools.createException(ErrorCodeEnum.operateOtherExceptionFailure);
        }
    }

    private void checkGoodsPrice(GoodsInfoWithBLOBs gi, List<GoodsSku> skuLists) {
        List<GoodsClassifyRebate> distRebateList = rebateService.selectListBySellID(SystemContext.getCompanyID(), 1);
        if (distRebateList == null || distRebateList.isEmpty()) {
            throw new ServiceException("平台商品分销系数未设置");
        }
        Map<String, Object> rebateMap = new HashMap<String, Object>();
        for (GoodsClassifyRebate goodsClassifyRebate : distRebateList) {
            rebateMap.put(goodsClassifyRebate.getClazzID(), goodsClassifyRebate);
        }
        GoodsClassifyRebate rebate = (GoodsClassifyRebate) rebateMap.get(gi.getSubClassifyID());
        for (GoodsSku sku : skuLists) {
            BigDecimal commissionGrade1 = sku.getPrice().multiply(BigDecimal.valueOf(rebate.getBankVal())).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
            if (commissionGrade1.compareTo(sku.getWholeSalePrice()) < 0) {
                throw new ServiceException("一级代理商供货价小于供应商供货价");
            }
        }

    }

    /**
     * @param
     * @return
     * @Author Tim Peng
     * @Description 店铺批量上架
     * @Date 2018/7/12 14:31
     */
    @Transactional
    public Object batchCopyGoods(BatchOnsaleDto batchOnsaleDto) {
        List<GoodsDetailsVo> goodsDetailsVos = batchOnsaleDto.getGoodsDetailsVos();
        Integer distGrade = getShopDistGrade(batchOnsaleDto.getShopID());
        for (GoodsDetailsVo goodsDetailsVo : goodsDetailsVos) {
            GoodsInfoVo goodsInfoVo = goodsDetailsVo.getGoodsInfoVo();
            List<GoodsSku> oldGoodsSkus = goodsSkuMapper.selectByGoodsID(goodsInfoVo.getGoodsID());
            List<GoodsSku> goodsSkuList = new ArrayList<>();
            goodsInfoVo.setSupplierID(batchOnsaleDto.getShopID());
            switch (batchOnsaleDto.getPriceType()) {
                case 1:
                    for (GoodsSku goodsSku : oldGoodsSkus) {
                        GoodsSku sku = new GoodsSku();
                        sku.setSkuID(goodsSku.getSkuID());
                        sku.setPrice(goodsSku.getPrice());
                        goodsSkuList.add(sku);
                    }
                    break;
                case 2:
                    for (GoodsSku goodsSku : oldGoodsSkus) {
                        GoodsSku sku = new GoodsSku();
                        sku.setSkuID(goodsSku.getSkuID());
                        sku.setPrice(getPriceGoodsAndShop(goodsDetailsVo.getGoodsInfoVo().getGoodsID(), distGrade, goodsSku.getSkuID(), batchOnsaleDto.getUpPrice()));
                        goodsSkuList.add(sku);
                    }
                    break;
                default:
                    throw new ServiceException("上架价格类型错误");
            }
            goodsDetailsVo.setGoodsSkuList(goodsSkuList);
            copyGoods(goodsDetailsVo);
        }
        return "success";
    }

    public BigDecimal getSkuPriceBySkuID(Long skuID) {
        GoodsSku sku = goodsSkuMapper.selectByPrimaryKey(skuID);
        return sku.getPrice();
    }

    /**
     * @return
     * @Author Tim Peng
     * @Description 获取零售价 或附加费
     * @Date 2018/7/12 17:12
     */
    public BigDecimal getPriceGoodsAndShop(Long goodsID, Integer distGrade, Long skuID, BigDecimal upPrice) {
        GoodsSku item = goodsSkuMapper.selectByPrimaryKey(skuID);
        GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(goodsID);

        if (goodsInfo.getPriceType() == 1) {
            return upPrice;
        }
        List<GoodsClassifyRebate> distRebateList = rebateService.selectListBySellID(SystemContext.getCompanyID(), 1);
        if (distRebateList == null || distRebateList.isEmpty()) {
            throw new ServiceException("分销系数资料未设置");
        }
        Map<String, Object> rebateMap = new HashMap<String, Object>();
        for (GoodsClassifyRebate goodsClassifyRebate : distRebateList) {
            rebateMap.put(goodsClassifyRebate.getClazzID(), goodsClassifyRebate);
        }
        GoodsClassifyRebate rebate = (GoodsClassifyRebate) rebateMap.get(goodsInfo.getClassifyID());
        BigDecimal price = BigDecimal.ZERO;
        switch (distGrade.intValue()) {
            case 2:
                //一级代理
                price = (item.getWholeSalePrice().add(item.getWholeSalePrice().multiply(BigDecimal.valueOf(rebate.getBankVal())).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP)));
                break;
            case 3:
                //二级代理
                price = (item.getWholeSalePrice().add(item.getWholeSalePrice().multiply(BigDecimal.valueOf(rebate.getEmployeeVal())).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP)));
                break;
            case 4:
                //三级代理
                price = (item.getWholeSalePrice().add(item.getWholeSalePrice().multiply(BigDecimal.valueOf(rebate.getThirdVal())).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP)));
                break;
        }
        return price.add(price.multiply(upPrice).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));

    }

    public Integer getShopDistGrade(Long shopID) {
        //查找商城， 找店长和老板
        DataResult result = HttpUtil.httpGet(ProConstants.BASE + "/organizational/queryOrginfo/" + shopID, restTemplate);
        if (result.getIsSuccess() == 0 || result.getData() == null) {
            throw new ServiceException("获取商城资料失败");
        }
        Map<String, Object> orginfo = (Map<String, Object>) result.getData();
        //当前分销商级别
        Integer distGrade = MapUtils.getInteger(orginfo, "level");

        return distGrade;
    }

    /**
     * 保存代销商品，店长从平台商城选择商品作为自己的店铺商品。
     * 即复制原来的商品信息，商品图片，sku，店铺可以定制自己的店铺零售价格
     * 传入参数
     * {
     * "goodsInfoVo": {
     * "goodsID": 929986728071008256, -- 平台商城商品goodsID
     * "supplierID":924092234591109120,  -- 店铺id
     * "supplierName": "梦缘珠宝" -- 店铺id
     * },
     * "goodsSkuList": [
     * {
     * "price": 1999, -- 店铺零售价
     * "skuID": 929986728091979777 -- 平台商城商品SKUID
     * }
     * ]
     * }
     *
     * @param goodsDetailsVo
     * @return
     * @date 2018-3-20
     */
    @Transactional
    public Long copyGoods(GoodsDetailsVo goodsDetailsVo) {
        try {

            //代销商品ID
            Long sourceGoodsId = goodsDetailsVo.getGoodsInfoVo().getGoodsID();

            Long shopID = goodsDetailsVo.getGoodsInfoVo().getSupplierID();
            if (shopID == null) {
                throw CommonTools.createException(ErrorCodeEnum.shopNoExist);
            }
            // 获取商品信息和label信息
            GoodsInfo tempGoods = goodsInfoMapper.selectByPrimaryKey(sourceGoodsId);
            if (tempGoods == null) {
                throw CommonTools.createException(ErrorCodeEnum.goodsNoExist);
            }

            GoodsShop oldGoodsShop = goodsShopMapper.selectByGoodsIDAndShopID(sourceGoodsId, shopID);
            if (oldGoodsShop != null) {
                throw CommonTools.createException(ErrorCodeEnum.shopGoodsOnsale);
            }
            // 获取sku信息和库存(数量、价格)
            List<GoodsSku> tmpGoodsSkuList = goodsSkuMapper.selectByGoodsID(sourceGoodsId);
            checkGoodsPriceByShop(tempGoods, goodsDetailsVo.getGoodsSkuList(), shopID);
            Long skuid = null;
            for (GoodsSku goodsSku : tmpGoodsSkuList) {
                skuid = goodsSku.getSkuID();
                for (GoodsSku goodsSkuTmp : goodsDetailsVo.getGoodsSkuList()) {
                    if (skuid.equals(goodsSkuTmp.getSkuID())) {
                        //店铺定义的价格
                        if (tempGoods.getPriceType() == 0 && goodsSkuTmp.getPrice().compareTo(goodsSku.getPrice().multiply(BigDecimal.valueOf(5))) == 1) {//普通商品大于建议零售价5倍，按零售价五倍处理
                            goodsSku.setPrice(goodsSku.getPrice().multiply(BigDecimal.valueOf(5)));
                        } else {
                            goodsSku.setPrice(goodsSkuTmp.getPrice());
                        }

                    }
                }
            }
            GoodsInfoWithBLOBs gi = new GoodsInfoWithBLOBs();
            BeanUtils.copyProperties(tempGoods, gi);
            gi.setShopID(shopID);

            // 2.保存规格(sku)到sku表
            batchInsertShopGoodsSkuInfo(gi, tmpGoodsSkuList, OperateTypeEnum.insert);

            //3.插入主表信息
            GoodsShop goodsShop = new GoodsShop();
            goodsShop.setGoodsID(sourceGoodsId);
            goodsShop.setShopID(shopID);
            goodsShop.setGoodsShopID(IdGen.get().nextId());
            goodsShop.setPrice(gi.getPrice());
            goodsShop.setLabelID(goodsDetailsVo.getGoodsInfoVo().getLabelID());

            goodsShopMapper.insertSelective(goodsShop);

            return gi.getGoodsID();
        } catch (ServiceException se) {
            logger.info(se.getMessage());
            throw se;
        } catch (Exception e) {
            logger.info(e.getMessage());
            throw CommonTools.createException(ErrorCodeEnum.operateOtherExceptionFailure);
        }
    }

    private void checkGoodsPriceByShop(GoodsInfo tempGoods, List<GoodsSku> skuLists, Long shopID) {
        List<GoodsClassifyRebate> distRebateList = rebateService.selectListBySellID(SystemContext.getCompanyID(), 1);
        if (distRebateList == null || distRebateList.isEmpty()) {
            throw new ServiceException("平台商品分销系数未设置");
        }
        Map<String, Object> rebateMap = new HashMap<String, Object>();
        for (GoodsClassifyRebate goodsClassifyRebate : distRebateList) {
            rebateMap.put(goodsClassifyRebate.getClazzID(), goodsClassifyRebate);
        }
        //代理商分成比例
        GoodsClassifyRebate rebate = (GoodsClassifyRebate) rebateMap.get(tempGoods.getSubClassifyID());
        if (distRebateList == null) {
            throw new ServiceException("平台商品分类的分销系数未设置");
        }

        //奖金分成系数
        List<GoodsClassifyRebate> comminRebateList = rebateService.selectListBySellID(shopID, 2);

        Map<String, Object> rebateProfitMap = new HashMap<String, Object>();
        if (comminRebateList == null || comminRebateList.isEmpty()) {
            throw new ServiceException("商城奖金系数未设置");
        }
        for (GoodsClassifyRebate goodsClassifyRebate : comminRebateList) {
            rebateProfitMap.put(goodsClassifyRebate.getClazzID(), goodsClassifyRebate);
        }
        //店长店员顾问佣金比例
        GoodsClassifyRebate rebateProfit = (GoodsClassifyRebate) rebateProfitMap.get(tempGoods.getSubClassifyID());
        logger.info("rebateProfit===" + rebateProfit);
        if (rebateProfit == null) {
            throw new ServiceException("店铺佣金比例系数未设置");
        }
        for (GoodsSku sku : skuLists) {
            GoodsSku oldSku = goodsSkuMapper.selectByPrimaryKey(sku.getSkuID());

            BigDecimal resalePrice = sku.getPrice();//零售价
            if (tempGoods.getPriceType() == 1) {//实时金价商品
                oldSku.setWholeSalePrice(getTodayGoldPrice(tempGoods.getSupplierID(), tempGoods.getAttr(), oldSku.getAttrJson()));
                resalePrice = getTodayGoldPriceByOtherFee(tempGoods.getSupplierID(), tempGoods.getAttr(), oldSku.getAttrJson(), sku.getPrice());
            }

            BigDecimal commissionGrade1 = getAgencyAdd(oldSku.getAttrJson(), rebate.getBankVal());
            // BigDecimal commissionGrade2 = oldSku.getWholeSalePrice().multiply(BigDecimal.valueOf(rebate.getEmployeeVal())).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
            //BigDecimal commissionGrade3 = oldSku.getWholeSalePrice().multiply(BigDecimal.valueOf(rebate.getThirdVal())).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);

            BigDecimal deductionRate = resalePrice.multiply(BigDecimal.valueOf(rebate.getDeductionRate())).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
            //店铺奖金分配
            BigDecimal commEmploy = resalePrice.multiply(new BigDecimal(rebateProfit.getEmployeeVal())).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
            BigDecimal commStoreMng = resalePrice.multiply(new BigDecimal(rebateProfit.getBankVal())).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
            BigDecimal commSalesMng = resalePrice.multiply(new BigDecimal(rebateProfit.getThirdVal())).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
            BigDecimal profit = resalePrice.subtract(commEmploy).subtract(commStoreMng).subtract(commSalesMng).subtract(commissionGrade1).subtract(deductionRate).subtract(oldSku.getWholeSalePrice());
            if (profit.compareTo(BigDecimal.ZERO) < 0) {
                throw new ServiceException("设置失败，可能没有利润");
            }
        }

    }


    /**
     * 查询商品详情
     *
     * @param goodsID isEdit  是否是编辑页面
     * @return
     */
    public GoodsDetailsVo queryGoodsDetail(Long goodsID, boolean isAndroid, boolean isEdit) {
        try {
            GoodsDetailsVo detail = new GoodsDetailsVo();
            // 获取商品信息和label信息
            GoodsInfo temp = goodsInfoMapper.selectByPrimaryKey(goodsID);
            if (temp == null) {
                throw CommonTools.createException(ErrorCodeEnum.goodsNoExist);
            }
            // 生产环境APP版本太低提醒更新后台处理 added by tim peng 2017-5-24
            /*if (isAndroid && temp.getClassifyID().equalsIgnoreCase(orderService.getGoldenClassifyID())) {
                throw new ServiceException("您当前版本太低，请更新后再使用.", RestConst.ErrorCode.SERVICE_FAIL);
            }*/
            detail.setGoodsInfoVo(new GoodsInfoVo());
            BeanUtils.copyProperties(temp, detail.getGoodsInfoVo());

            // 获取图片信息
            List<GoodsImages> goodsImages = goodsImagesMapper.selectByGoodsID(goodsID);
            List<String> goodsUrls = new ArrayList<String>();
            for (GoodsImages goodsImage : goodsImages) {
                goodsUrls.add(goodsImage.getUrl());
            }
            detail.setImageUrlList(goodsUrls);

            //获取标签列表
            detail.setGoodsTagList(goodsTagMapper.selectListByGoodsId(goodsID));

            // 获取sku信息和库存(数量、价格)
            List<GoodsSku> goodsSkuList = goodsSkuMapper.selectByGoodsID(goodsID);
            detail.setGoodsSkuList(goodsSkuList);
            //计算实时金价
            if (temp.getPriceType() == 1 && goodsSkuList.size() > 0 && !isEdit) {
                for (int i = 0; i < goodsSkuList.size(); i++) {
                    goodsSkuList.get(i).setPrice(getTodayGoldPriceByOtherFee(temp.getSupplierID(), temp.getAttr(), goodsSkuList.get(i).getAttrJson(), goodsSkuList.get(i).getPrice()));
                    goodsSkuList.get(i).setWholeSalePrice(getTodayGoldPrice(temp.getSupplierID(), temp.getAttr(), goodsSkuList.get(i).getAttrJson()));//供货价
                }
            }
            //获取供应商信息
            detail.setSupperlierInfo(remoteGetSupplierInfo(temp.getSupplierID()));
            return detail;
        } catch (ServiceException se) {
            logger.info(se.getMessage());
            throw se;
        } catch (Exception e) {
            throw CommonTools.createException(ErrorCodeEnum.queryGoodsDetailFailure);
        }
    }


    /**
     * @param supplierID  供应商ID
     * @param goodsAttr   商品信息attr
     * @param skuAttrJson 商品属性attrJson
     * @return
     */
    public BigDecimal getTodayGoldPrice(Long supplierID, String goodsAttr, String skuAttrJson) {
        List<JSONObject> jsonList = JsonUtil.toList(goodsAttr);
        StringBuffer necklace = new StringBuffer();

        for (JSONObject obj : jsonList) {//取得成色
            System.out.print(obj);
            if (obj.get("clazzattrcode").equals("neckcure")) {
                necklace.append(obj.get("clazzattrval").toString());
            }
        }

        //获取实时金价
        /*JSONObject jsonObject = HttpUtil.httpGetJSONObject(ProConstants.getTodayGoldPriceByNecklace + supplierID + "/" + necklace, restTemplate);
        if (!com.google.common.base.Objects.equal(DataUtils.getInteger(jsonObject, "isSuccess"), 1)) {
            throw new ServiceException("调用base服务获取实时金价接口出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        BigDecimal price = new BigDecimal(jsonObject.get("data").toString());
*/

        BigDecimal price = getGoldPrice(necklace);
        //克重
        Map skuMap = JsonUtil.toMap(skuAttrJson);
        BigDecimal goldWeight = new BigDecimal(null == skuMap.get("weight") ? "0" : skuMap.get("weight").toString());
        BigDecimal craftFeeB = new BigDecimal(null == skuMap.get("wage") ? "0" : skuMap.get("wage").toString());
        //Arith.round(Arith.mul(price, goldWeight).add(craftFeeB).doubleValue(), 2);
        logger.info("goldWeight=====" + goldWeight);
        logger.info("craftFeeB=====" + craftFeeB);
        return price.add(craftFeeB).multiply(goldWeight).setScale(2, BigDecimal.ROUND_HALF_UP);

    }

    public BigDecimal getGoldPrice(StringBuffer necklace) {

        String url = ProConstants.getNowGoldPrice + "/" + necklace;
        logger.info("url=====" + url);

        //获取实时金价
        DataResult result = HttpUtil.httpGet(url, restTemplate);
        if (result.getIsSuccess() == 0) {
            throw new ServiceException("调用point服务获取实时金价接口出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        BigDecimal price = new BigDecimal(result.getData().toString());
        if (price == null || price.compareTo(BigDecimal.ZERO) == 0) {
            throw new ServiceException("调用point服务获取实时金价接口出错", RestConst.ErrorCode.SERVICE_FAIL);
        }

        logger.info("price=====" + price);

        return price;
    }


    /**
     * @param supplierID  供应商ID
     * @param goodsAttr   商品信息attr
     * @param skuAttrJson 商品属性skuAttrJson
     * @param otherFee    附加费用
     * @return
     * @Author Tim Peng
     * @Description 小商城实时金价
     * @Date 2018/6/20 15:35
     */
    public BigDecimal getTodayGoldPriceByOtherFee(Long supplierID, String goodsAttr, String skuAttrJson, BigDecimal otherFee) {
        List<JSONObject> jsonList = JsonUtil.toList(goodsAttr);
        StringBuffer necklace = new StringBuffer();

        for (JSONObject obj : jsonList) {//取得成色
            System.out.print(obj);
            if (obj.get("clazzattrcode").equals("neckcure")) {
                necklace.append(obj.get("clazzattrval").toString());
            }
            logger.info("necklace=====" + necklace);
        }

        //获取实时金价
        /*JSONObject jsonObject = HttpUtil.httpGetJSONObject(ProConstants.getTodayGoldPriceByNecklace + supplierID + "/" + necklace, restTemplate);
        if (!com.google.common.base.Objects.equal(DataUtils.getInteger(jsonObject, "isSuccess"), 1)) {
            throw new ServiceException("调用base服务获取实时金价接口出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        BigDecimal price = new BigDecimal(jsonObject.get("data").toString());*/

        String url = ProConstants.getNowGoldPrice + "/" + necklace;
        logger.info("url=====" + url);
        //获取实时金价
        DataResult result = HttpUtil.httpGet(url, restTemplate);
        if (result.getIsSuccess() == 0) {
            throw new ServiceException("调用point服务获取实时金价接口出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        BigDecimal price = new BigDecimal(result.getData().toString());
        if (price == null || price.compareTo(BigDecimal.ZERO) == 0) {
            throw new ServiceException("调用point服务获取实时金价接口出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        logger.info("price=====" + price);
        //克重
        Map skuMap = JsonUtil.toMap(skuAttrJson);
        BigDecimal goldWeight = new BigDecimal(null == skuMap.get("weight") ? "0" : skuMap.get("weight").toString());
        BigDecimal craftFeeB = new BigDecimal(null == skuMap.get("wage") ? "0" : skuMap.get("wage").toString());

        logger.info("goldWeight=====" + goldWeight);
        logger.info("craftFeeB=====" + craftFeeB);
        return price.add(craftFeeB).add(otherFee).multiply(goldWeight).setScale(2, BigDecimal.ROUND_HALF_UP);

    }

    /**
     * 查询商品详情v2
     * 带会员价
     *
     * @param goodsID
     * @return
     */
    public GoodsDetailsVo queryGoodsDetailv2(Long goodsID, Long userID, boolean isAndroid) {
        try {
            GoodsDetailsVo detail = new GoodsDetailsVo();
            // 获取商品信息和label信息
            GoodsInfo temp = goodsInfoMapper.selectByPrimaryKey(goodsID);
            if (temp == null) {
                throw CommonTools.createException(ErrorCodeEnum.goodsNoExist);
            }
            // 生产环境APP版本太低提醒更新后台处理 added by tim peng 2017-5-24
            /*if (isAndroid && temp.getClassifyID().equalsIgnoreCase(orderService.getGoldenClassifyID())) {
                throw new ServiceException("您当前版本太低，请更新后再使用.", RestConst.ErrorCode.SERVICE_FAIL);
            }*/
            detail.setGoodsInfoVo(new GoodsInfoVo());
            BeanUtils.copyProperties(temp, detail.getGoodsInfoVo());

            // 获取图片信息
            List<GoodsImages> goodsImages = goodsImagesMapper.selectByGoodsID(goodsID);
            List<String> goodsUrls = new ArrayList<String>();
            for (GoodsImages goodsImage : goodsImages) {
                goodsUrls.add(goodsImage.getUrl());
            }
            detail.setImageUrlList(goodsUrls);

            // 获取sku信息和库存(数量、价格)
            Long VipPriceSW = getVipPriceSW(SystemContext.getCompanyID());
            List<GoodsSku> goodsSkuList = new ArrayList<>();
            if (2l == VipPriceSW && temp.getPriceType() == 0) {//会员价开启
                UserInfoForOrderDto userInfoForOrderDto = (UserInfoForOrderDto) getUserInfoForOrder(userID);
                goodsSkuList = goodsSkuMapper.selectByGoodsIDv2(goodsID, userInfoForOrderDto.getVipLevel());
            } else {
                goodsSkuList = goodsSkuMapper.selectByGoodsIDv2(goodsID, 1l);
                //计算实时金价
                if (temp.getPriceType() == 1 && goodsSkuList.size() > 0) {
                    for (int i = 0; i < goodsSkuList.size(); i++) {
                        goodsSkuList.get(i).setPrice(getTodayGoldPriceByOtherFee(temp.getSupplierID(), temp.getAttr(), goodsSkuList.get(i).getAttrJson(), goodsSkuList.get(i).getPrice()));
                    }
                }
            }
            detail.setGoodsSkuList(goodsSkuList);
            //获取供应商信息
            detail.setSupperlierInfo(remoteGetSupplierInfo(temp.getSupplierID()));
            return detail;
        } catch (ServiceException se) {
            throw se;
        } catch (Exception e) {
            throw CommonTools.createException(ErrorCodeEnum.queryGoodsDetailFailure);
        }
    }


    /**
     * 条件查询
     *
     * @param queryGoodsDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Object conditionQueryGoods(QueryGoodsDto queryGoodsDto, Integer pageNum, Integer pageSize) {

        String orderBy = "addTime";
        String orderType = "desc";
        queryGoodsDto.setCompanyID(SystemContext.getCompanyID());
        if (CommonUtils.isNotEmpty(queryGoodsDto.getOrderBy())) {
            orderBy = queryGoodsDto.getOrderBy();
        }
        if (CommonUtils.isNotEmpty(queryGoodsDto.getOrderType()) && queryGoodsDto.getOrderType().equals("asc")) {
            orderType = queryGoodsDto.getOrderType();
        }
        String orderStr = "info." + orderBy + " " + orderType;
        PageHelper.startPage(pageNum, pageSize, orderStr);//分页初始化
        Page page = (Page) goodsInfoMapper.selectCondition(queryGoodsDto);

        //查看代理价格
//        if (queryGoodsDto.getShopID() != null) {
//            for (QueryResultGoodsDto goods : (List<QueryResultGoodsDto>) page.getResult()) {
//                List<GoodsSku> listSKU = (List<GoodsSku>) queryGoodsSkuInfo(goods.getGoodsID(), queryGoodsDto.getShopID(), goods.getClassifyID());
//                if (!listSKU.isEmpty()) {
//                    ListUtils.sort(listSKU, true, "vipPrice");
//                }
//            }
//        }
        return new PageInfo(page, page.getPages(), page.getTotal());
    }

    public Object conditionQueryGoodsV2(QueryGoodsDto queryGoodsDto, Integer pageNum, Integer pageSize) {

        String orderBy = "addTime";
        String orderType = "desc";
        queryGoodsDto.setCompanyID(SystemContext.getCompanyID());
        if (CommonUtils.isNotEmpty(queryGoodsDto.getOrderBy())) {
            orderBy = queryGoodsDto.getOrderBy();
        }
        if (CommonUtils.isNotEmpty(queryGoodsDto.getOrderType()) && queryGoodsDto.getOrderType().equals("asc")) {
            orderType = queryGoodsDto.getOrderType();
        }
        String orderStr = "info." + orderBy + " " + orderType;
        PageHelper.startPage(pageNum, pageSize, orderStr);//分页初始化
        List<QueryResultGoodsDto> goodsList = goodsInfoMapper.selectConditionV2(queryGoodsDto);

        if (Objects.equal(queryGoodsDto.getPriceType(), 0)) {//普通商品查询代理价
            List<GoodsClassifyRebate> distRebateList = rebateService.selectListBySellID(SystemContext.getCompanyID(), 1);
            if (distRebateList == null || distRebateList.isEmpty()) {
                throw new ServiceException("分销系数资料未设置");
            }
            for (QueryResultGoodsDto resultGoods : goodsList) {
                resultGoods.setAgencyPrice(getGoodsAgencyPrice(resultGoods, queryGoodsDto.getShopID(), distRebateList));
            }

        }

        Page page = (Page) goodsList;

        return new PageInfo(page, page.getPages(), page.getTotal());
    }

    private BigDecimal getGoodsAgencyPrice(QueryResultGoodsDto resultGoods, Long shopID, List<GoodsClassifyRebate> distRebateList) {
        List<GoodsSku> skuList = goodsSkuMapper.selectByGoodsID(resultGoods.getGoodsID());
        Map<String, Object> rebateMap = new HashMap<String, Object>();
        for (GoodsClassifyRebate goodsClassifyRebate : distRebateList) {
            rebateMap.put(goodsClassifyRebate.getClazzID(), goodsClassifyRebate);
        }
        GoodsClassifyRebate rebate = (GoodsClassifyRebate) rebateMap.get(resultGoods.getSubClassifyID());
        List<BigDecimal> prices = new ArrayList<>();
        for (GoodsSku item : skuList) {
            BigDecimal agencyPrice = item.getWholeSalePrice().add(item.getWholeSalePrice().multiply(BigDecimal.valueOf(rebate.getBankVal())).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP));
            prices.add(agencyPrice);
        }

        BigDecimal lowPrice = prices.get(0);
        for (int i = 0; i < prices.size(); i++) {
            if (prices.get(i).compareTo(lowPrice) == -1) {
                lowPrice = prices.get(i);
            }
        }
        //返回最低价格
        return lowPrice;

    }


    /**
     * 条件查询
     *
     * @param queryGoodsDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Object conditionQueryShopGoods(QueryGoodsDto queryGoodsDto, Integer pageNum, Integer pageSize) {

        String orderBy = "addTime";
        String orderType = "desc";
        if (CommonUtils.isNotEmpty(queryGoodsDto.getOrderBy())) {
            orderBy = queryGoodsDto.getOrderBy();
        }
        if (CommonUtils.isNotEmpty(queryGoodsDto.getOrderType()) && queryGoodsDto.getOrderType().equals("asc")) {
            orderType = queryGoodsDto.getOrderType();
        }

        String searchSource =  "info.";
        if (orderBy.equals("weight")){
            searchSource="stone.";
        }
        String orderStr =searchSource + orderBy + " " + orderType;

        /*if (CommonUtils.isNotEmpty(queryGoodsDto.getOrderBy()) && queryGoodsDto.getOrderBy().equals("seqno")) {//根据标签排序的特殊标记
            orderStr = "label.seqno asc";
        }*/

        PageHelper.startPage(pageNum, pageSize, orderStr);//分页初始化
        Page page = (Page) goodsInfoMapper.selectShopCondition(queryGoodsDto);

        //查看代理价格
 /*       if (queryGoodsDto.getShopID() != null) {
            for (QueryResultGoodsDto goods : (List<QueryResultGoodsDto>) page.getResult()) {
                List<GoodsSku> listSKU = (List<GoodsSku>) queryGoodsSkuInfo(goods.getGoodsID(), queryGoodsDto.getShopID(), goods.getClassifyID());
                if (!listSKU.isEmpty()) {
                    ListUtils.sort(listSKU, true, "vipPrice");
                }
            }
        }*/
        return new PageInfo(page, page.getPages(), page.getTotal());
    }

    /**
     * 查询商品sku信息
     * added
     *
     * @param goodsID
     * @return
     */
    public Object queryGoodsSkuInfo(Long goodsID, Long shopID, String classifyID) {
        List<GoodsSku> skuList = goodsSkuMapper.selectByGoodsID(goodsID);
        GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(goodsID);

        // added 根据商城ID计算拿货价
        if (shopID != null && !Objects.equal(shopID, 0L)) {
            //查找商城， 找店长和老板
            DataResult result = HttpUtil.httpGet(ProConstants.BASE + "/organizational/queryOrginfo/" + shopID, restTemplate);
            if (result.getIsSuccess() == 0 || result.getData() == null) {
                throw new ServiceException("获取商城资料失败");
            }
            Map<String, Object> orginfo = (Map<String, Object>) result.getData();
            //当前分销商级别
            Integer distGrade = MapUtils.getInteger(orginfo, "level");
            List<GoodsClassifyRebate> distRebateList = rebateService.selectListBySellID(SystemContext.getCompanyID(), 1);
            if (distRebateList == null || distRebateList.isEmpty()) {
                throw new ServiceException("分销系数资料未设置");
            }
            Map<String, Object> rebateMap = new HashMap<String, Object>();
            for (GoodsClassifyRebate goodsClassifyRebate : distRebateList) {
                rebateMap.put(goodsClassifyRebate.getClazzID(), goodsClassifyRebate);
            }
            GoodsClassifyRebate rebate = (GoodsClassifyRebate) rebateMap.get(classifyID);
            if (goodsInfo.getPriceType() == 1) {//实时金价供货价
                for (GoodsSku item : skuList) {
                    item.setWholeSalePrice(getTodayGoldPrice(goodsInfo.getSupplierID(), goodsInfo.getAttr(), item.getAttrJson()));
                }
            }
            for (GoodsSku item : skuList) {
                switch (distGrade.intValue()) {
                    case 2:
                        //一级代理
                        if (goodsInfo.getPriceType() == 1) {
                            item.setVipPrice(item.getWholeSalePrice().add(getAgencyAdd(item.getAttrJson(), rebate.getBankVal())));// (工费+金价)*克重 +(工费*克重)*系数
                            item.setAttrJson(setNewAgencyWage(rebate.getBankVal(), item.getAttrJson(), goodsInfo.getAttr())); //修改工费
                            // item.setViphPrice(getGoodsByGoldPrice(goodsInfo.getAttr()));//临时借用为实时金价
                        } else {
                            item.setVipPrice(item.getWholeSalePrice().add(item.getWholeSalePrice().multiply(BigDecimal.valueOf(rebate.getBankVal())).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP)));
                        }

                        break;
                    case 3:
                        //二级代理
                        if (goodsInfo.getPriceType() == 1) {
                            item.setVipPrice(item.getWholeSalePrice().add(getAgencyAdd(item.getAttrJson(), rebate.getEmployeeVal())));// (工费+金价)*克重 +(工费*克重)*系数
                            item.setAttrJson(setNewAgencyWage(rebate.getEmployeeVal(), item.getAttrJson(), goodsInfo.getAttr())); //修改工费
                            // item.setViphPrice(getGoodsByGoldPrice(goodsInfo.getAttr()));//临时借用为实时金价
                        } else {
                            item.setVipPrice(item.getWholeSalePrice().add(item.getWholeSalePrice().multiply(BigDecimal.valueOf(rebate.getEmployeeVal())).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP)));
                        }
                        break;
                    case 4:
                        //三级代理
                        if (goodsInfo.getPriceType() == 1) {
                            item.setVipPrice(item.getWholeSalePrice().add(getAgencyAdd(item.getAttrJson(), rebate.getThirdVal())));// (工费+金价)*克重 +(工费*克重)*系数
                            item.setAttrJson(setNewAgencyWage(rebate.getThirdVal(), item.getAttrJson(), goodsInfo.getAttr())); //修改工费
                            //  item.setViphPrice(getGoodsByGoldPrice(goodsInfo.getAttr()));//临时借用为实时金价
                        } else {
                            item.setVipPrice(item.getWholeSalePrice().add(item.getWholeSalePrice().multiply(BigDecimal.valueOf(rebate.getThirdVal())).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP)));
                        }
                        break;
                }
            }
        }
        return skuList;
    }

    public BigDecimal getGoodsByGoldPrice(String goodsAttr) {
        List<JSONObject> jsonList = JsonUtil.toList(goodsAttr);
        StringBuffer necklace = new StringBuffer();

        for (JSONObject obj : jsonList) {//取得成色
            System.out.print(obj);
            if (obj.get("clazzattrcode").equals("neckcure")) {
                necklace.append(obj.get("clazzattrval").toString());
            }
        }

        return getGoldPrice(necklace);
    }

    public BigDecimal getAgencyAdd(String skuAttrJson, Integer val) {//获取实时金价商品平台加价
        //(工费*克重)*系数
        Map skuMap = JsonUtil.toMap(skuAttrJson);
        BigDecimal goldWeight = new BigDecimal(null == skuMap.get("weight") ? "0" : skuMap.get("weight").toString());
        BigDecimal craftFeeB = new BigDecimal(null == skuMap.get("wage") ? "0" : skuMap.get("wage").toString());
        BigDecimal fee = craftFeeB.multiply(goldWeight).multiply(BigDecimal.valueOf(val)).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
        return fee;
    }

    public String setNewAgencyWage(Integer val, String attrJson, String goodsAttr) {//获取代理商工费   供应商工费+供应商工费*系数

        JSONObject skuAttrs = JSONObject.fromObject(attrJson);
        if (skuAttrs.containsKey("wage")) {
            BigDecimal wage = BigDecimal.valueOf(skuAttrs.getDouble("wage"));
            BigDecimal newWage = wage.add(wage.multiply(BigDecimal.valueOf(val)).divide(new BigDecimal(1000))).setScale(2, BigDecimal.ROUND_HALF_UP);

            String name = skuAttrs.get("name") + "";
            JSONObject nameJson = new JSONObject();
            if (CommonUtils.isNotEmpty(name)) {
                String[] a = name.split("\\+");
                for (int i = 0; i < a.length; i++) {
                    String[] b = a[i].split(":");
                    if (Objects.equal(b.length, 2)) {
                        nameJson.put(a[i].split(":")[0], a[i].split(":")[1]);
                    }
                }
            }
            nameJson.put("工费", newWage + "元/克");
            nameJson.put("实时金价", getGoodsByGoldPrice(goodsAttr));
            skuAttrs.put("wage", newWage);
            skuAttrs.put("name", getAttrNameByJson(nameJson));
        }

        return skuAttrs.toString();
    }

/*
    public String getTypeClassifyByID(String classifyID){
        JSONObject jsonObject = rest.getForObject(classifyByID+classifyID, JSONObject.class);
        logger.info("jsonObject="+jsonObject.toString());

        if (jsonObject.getInt("isSuccess") != 1) {
            throw new ServiceException("调用云管控服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        JSONObject jsonObj = jsonObject.getJSONObject("data");
        String other2 = DataUtils.getStr(jsonObj,"other2","1");
    }
*/


    /**
     * 供货商 修改商品sku库存和价格
     *
     * @param goodsSkuVo
     * @return
     */
    @Transactional
    public Object operateGoodsSkuInventory(GoodsSkuVo goodsSkuVo) {
        int result = 0;
        GoodsInfoWithBLOBs gi = goodsInfoMapper.selectByPrimaryKey(goodsSkuVo.getGoodsID());
        if (gi == null) {
            throw CommonTools.createException(ErrorCodeEnum.goodsNoExist);
        }
        //仅修改库存 最低价赋值-1 否则赋值null
        BigDecimal lowstPrice = goodsSkuVo.getStatus() != 0 ? new BigDecimal("-1") : null;
        int totalInventory = 0;
        for (GoodsSkuDto goodsSkuDto : goodsSkuVo.getGoodsSkuList()) {

            //获得最低价格
            if (goodsSkuVo.getStatus() != 0) {
                goodsSkuDto.setPrice(goodsSkuDto.getPrice() == null ? new BigDecimal("0") : goodsSkuDto.getPrice());
                comparePrice(0, lowstPrice, goodsSkuDto.getPrice());
            } else {
                goodsSkuDto.setPrice(null);
            }

            if (goodsSkuVo.getStatus() != 1) {
                goodsSkuDto.setInventory(goodsSkuDto.getInventory() == null ? 0 : goodsSkuDto.getInventory());
                totalInventory += goodsSkuDto.getInventory();//库存累加
            } else {
                goodsSkuDto.setInventory(null);
            }
            result += goodsSkuMapper.updateByPrimaryKeySelective(goodsSkuDto);
        }
        GoodsInfoWithBLOBs updateGoods = new GoodsInfoWithBLOBs();
        updateGoods.setGoodsID(goodsSkuVo.getGoodsID());
        updateGoods.setInventory(goodsSkuVo.getStatus() != 1 ? totalInventory : updateGoods.getInventory());
        updateGoods.setPrice(goodsSkuVo.getStatus() != 0 ? lowstPrice : updateGoods.getPrice());
        updateGoods.setIsAudit(gi.getIsAudit());
        updateGoods.setOnsale(gi.getOnsale());
        //判断是否为已售罄状态，是 增加补仓操作
        if (gi.getSoldoutTime() != null && updateGoods.getIsAudit() == 1 && updateGoods.getOnsale() == 1 && updateGoods.getInventory() > 0) {
            updateGoods.setSoldoutTime(null);
            if (goodsInfoMapper.updateByPrimaryKeySelective(updateGoods) == 0) {
                throw CommonTools.createException(ErrorCodeEnum.operateGoodsInfoFailure);
            }
            goodsIndexService.addIndexing(updateGoods.getGoodsID());
            return result;
        }
        if (goodsInfoMapper.updateByPrimaryKeySelective(updateGoods) == 0) {
            throw CommonTools.createException(ErrorCodeEnum.operateGoodsInfoFailure);
        }
        return result;
    }

    /**
     * 操作商品状态
     *
     * @param goodsID
     * @param state
     * @return
     */
    @Transactional
    public Object operateGoodsStateV2(Long goodsID, GoodsStateEnum state, String labelID,
                                      List<GoodsSku> goodsSkuList) {
        GoodsStateInfoDto gsInfo = new GoodsStateInfoDto(goodsID);
        switch (state) {
            case Approved:
                gsInfo.setIsAudit(1);
                if (CommonUtils.isEmpty(labelID)) {
                    throw CommonTools.createException(ErrorCodeEnum.goodsNoLabel);
                }
                gsInfo.setLabelID(Long.parseLong(labelID));
                addPrice(goodsID, goodsSkuList);
                //通知购物车中该商品启用
                this.notifyGoodsCartExpire(goodsID, 1);

                break;
            case Unapprove:
                gsInfo.setIsAudit(2);
                break;
            case Unshelve:
                gsInfo.setOnsale(0);
                gsInfo.setIsAudit(0);
                //通知购物车中该商品失效
                this.notifyGoodsCartExpire(goodsID, 0);
                break;
            case Shelve:
                gsInfo.setOnsale(1);
                gsInfo.setIsAudit(0);
                break;
            case Detele:
                gsInfo.setIsStop(1);
                gsInfo.setOnsale(0);
                gsInfo.setIsAudit(0);
                //通知购物车中该商品失效
                this.notifyGoodsCartExpire(goodsID, 0);
                break;
            default:
                throw CommonTools.createException(ErrorCodeEnum.goodsParmsError);
        }
        //操作索引
        int result = goodsInfoMapper.updateGoodsState(gsInfo);
        if (result == 1) {
            goodsIndexService.operateIndexing(state, goodsID);
        }
        return 1;
    }

    @Transactional
    public Object operateGoodsStateV2Copy(Long goodsID, GoodsStateEnum state, String labelID,
                                          List<GoodsSku> goodsSkuList, GoodsPriceDto goodsPriceDto) {
        GoodsStateInfoDto gsInfo = new GoodsStateInfoDto(goodsID);
        switch (state) {
            case Approved:
                gsInfo.setIsAudit(1);
                if (CommonUtils.isEmpty(labelID)) {
                    throw CommonTools.createException(ErrorCodeEnum.goodsNoLabel);
                }
                gsInfo.setLabelID(Long.parseLong(labelID));
                addPrice(goodsID, goodsSkuList);
                //通知购物车中该商品启用
                this.notifyGoodsCartExpire(goodsID, 1);
                updateVal(goodsPriceDto);
                break;
            case Unapprove:
                gsInfo.setIsAudit(2);
                break;
            case Unshelve:
                gsInfo.setOnsale(0);
                gsInfo.setIsAudit(0);
                //通知购物车中该商品失效
                this.notifyGoodsCartExpire(goodsID, 0);
                break;
            case Shelve:
                gsInfo.setOnsale(1);
                gsInfo.setIsAudit(0);
                break;
            case Detele:
                gsInfo.setIsStop(1);
                gsInfo.setOnsale(0);
                gsInfo.setIsAudit(0);
                //通知购物车中该商品失效
                this.notifyGoodsCartExpire(goodsID, 0);
                break;
            default:
                throw CommonTools.createException(ErrorCodeEnum.goodsParmsError);
        }
        //操作索引
        int result = goodsInfoMapper.updateGoodsState(gsInfo);
        if (result == 1) {
            goodsIndexService.operateIndexing(state, goodsID);
        }
        return 1;
    }


    private void addPrice(Long goodsID, List<GoodsSku> goodsSkuList) {
        // 2.保存规格(sku)到sku表
        GoodsInfo gi = new GoodsInfo();
        gi.setGoodsID(goodsID);
        batchInsertGoodsSkuInfo(gi, goodsSkuList, OperateTypeEnum.update);
        //3.插入主表信息
        GoodsInfoWithBLOBs goodsInfoWithBLOBs = new GoodsInfoWithBLOBs();
        BeanUtils.copyProperties(gi, goodsInfoWithBLOBs);
        operateGoodsInfo(goodsInfoWithBLOBs, OperateTypeEnum.update);
    }

    /**
     * 操作商品状态
     * 中银金行审核保存商品价格
     *
     * @param goodsID
     * @param state
     * @return
     */
    @Transactional
    public Object operateGoodsState(Long goodsID, GoodsStateEnum state, String labelID) {
        GoodsStateInfoDto gsInfo = new GoodsStateInfoDto(goodsID);
        switch (state) {
            case Approved:
                gsInfo.setIsAudit(1);
                if (CommonUtils.isEmpty(labelID)) {
                    throw CommonTools.createException(ErrorCodeEnum.goodsNoLabel);
                }
                gsInfo.setLabelID(Long.parseLong(labelID));
                //通知购物车中该商品启用
                this.notifyGoodsCartExpire(goodsID, 1);
                break;
            case Unapprove:
                gsInfo.setIsAudit(2);
                break;
            case Unshelve:
                gsInfo.setOnsale(0);
                gsInfo.setIsAudit(0);
                //通知购物车中该商品失效
                this.notifyGoodsCartExpire(goodsID, 0);
                this.notifyShopGoodsExpire(goodsID, null);
                break;
            case Shelve:
                gsInfo.setOnsale(1);
                gsInfo.setIsAudit(0);
                break;
            case Detele:
                gsInfo.setIsStop(1);
                gsInfo.setOnsale(0);
                gsInfo.setIsAudit(0);
                //通知购物车中该商品失效
                this.notifyGoodsCartExpire(goodsID, 0);
                break;
            default:
                throw CommonTools.createException(ErrorCodeEnum.goodsParmsError);
        }
        //操作索引
        int result = goodsInfoMapper.updateGoodsState(gsInfo);
        if (result == 1) {
            goodsIndexService.operateIndexing(state, goodsID);
        }
        return 1;
    }

    /*private int updateVal(GoodsStateInfoDto gsInfo){
        if(!rebateService.isGoods()){
            return 0;
        }
        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setGoodsID(gsInfo.getGoodsID());
        goodsInfo.setGoodsID(gsInfo.getGoodsID());
        goodsInfo.setBankVal(gsInfo.getBankVal());
        goodsInfo.setEmployeeVal(gsInfo.getEmployeeVal());
        return goodsInfoMapper.updateVal(goodsInfo);
    }*/

    private int updateVal(GoodsPriceDto gsInfo) {
        if (!rebateService.isGoods()) {
            return 0;
        }
        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setGoodsID(gsInfo.getGoodsID());
        goodsInfo.setBankVal(gsInfo.getBankVal());
        goodsInfo.setEmployeeVal(gsInfo.getEmployeeVal());
        return goodsInfoMapper.updateVal(goodsInfo);
    }

    private int updateVal(GoodsInfoWithBLOBs gsInfo) {
        if (!rebateService.isGoods()) {
            return 0;
        }
        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setGoodsID(gsInfo.getGoodsID());
        goodsInfo.setBankVal(gsInfo.getBankVal());
        goodsInfo.setEmployeeVal(gsInfo.getEmployeeVal());
        return goodsInfoMapper.updateVal(goodsInfo);
    }

    private int updateVal2(GoodsInfoWithBLOBs gsInfo) {
        if (!rebateService.isGysGoods()) {
            return 0;
        }
        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setGoodsID(gsInfo.getGoodsID());
        goodsInfo.setBankVal(gsInfo.getBankVal());
        goodsInfo.setEmployeeVal(gsInfo.getEmployeeVal());
        return goodsInfoMapper.updateVal(goodsInfo);
    }


    /**
     * 操作商品状态
     * 中银金行审核保存商品价格
     *
     * @param goodsID
     * @param state
     * @return
     */
    @Transactional
    public Object operateGoodsStateCopy(Long goodsID, GoodsStateEnum state, String labelID, Map<String, Object> map) {
        GoodsStateInfoDto gsInfo = new GoodsStateInfoDto(goodsID);
        Integer bankVal = MapUtils.getInteger(map, "bankVal", 0);
        Integer employeeVal = MapUtils.getInteger(map, "employeeVal", 0);
        gsInfo.setBankVal(bankVal);
        gsInfo.setEmployeeVal(employeeVal);
        switch (state) {
            case Approved:
                gsInfo.setIsAudit(1);
                if (CommonUtils.isEmpty(labelID)) {
                    throw CommonTools.createException(ErrorCodeEnum.goodsNoLabel);
                }
                gsInfo.setLabelID(Long.parseLong(labelID));
                //通知购物车中该商品启用
                this.notifyGoodsCartExpire(goodsID, 1);
                //updateVal(gsInfo);
                break;
            case Unapprove:
                gsInfo.setIsAudit(2);
                break;
            case Unshelve:
                gsInfo.setOnsale(0);
                gsInfo.setIsAudit(0);
                //通知购物车中该商品失效
                this.notifyGoodsCartExpire(goodsID, 0);
                break;
            case Shelve:
                gsInfo.setOnsale(1);
                gsInfo.setIsAudit(0);
                break;
            case Detele:
                gsInfo.setIsStop(1);
                gsInfo.setOnsale(0);
                gsInfo.setIsAudit(0);
                //通知购物车中该商品失效
                this.notifyGoodsCartExpire(goodsID, 0);
                break;
            default:
                throw CommonTools.createException(ErrorCodeEnum.goodsParmsError);
        }
        //操作索引
        int result = goodsInfoMapper.updateGoodsState(gsInfo);
        if (result == 1) {
            goodsIndexService.operateIndexing(state, goodsID);
        }
        return 1;
    }

    /**
     * 下单 改变商品sku库存
     *
     * @param operateType 0 订单失效or取消 加库存 1 下单成功 预减库存 2 支付成功 减库存 加销量 4撤销回滚库存
     * @param skuID
     * @param number      库存改变值
     * @return
     */
    @Transactional
    public boolean changeInventory(int operateType, Long goodsID, Long skuID, int number, Long orderNo) {
        try {
            String redisKey = orderNo + "||" + skuID;
            switch (operateType) {
                case 0:
                    if (goodsSkuMapper.addInventoryBySkuID(skuID, number) == 0) {
                        return false;
                    }
                    break;
                case 1:
                    //预消减库存
                    int result = goodsSkuMapper.subtractInventoryBySkuID(skuID, number);
                    if (result == 0) {//失败
                        return false;
                    }
                    break;
                case 3:
                    //借货归还+库存
                    int result2 = goodsSkuMapper.addInventoryBySkuID(skuID, number);
                    if (result2 == 0) {//失败
                        return false;
                    }
                    break;
                case 2:
                    //减库存 加销量
                    if (goodsInfoMapper.opeateInventoryOrSales(number, -number, goodsID) == 0) {
                        throw CommonTools.createException(ErrorCodeEnum.goodsInventoryShortage);
                    }

                    //更新商品索引 销量信息
                    GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(goodsID);
                    GoodsIndexInfoVo index = new GoodsIndexInfoVo();
                    index.setGoodsID(goodsID);
                    index.setSalas(goodsInfo.getSales());
                    if (goodsInfo.getInventory() == 0) {
                        goodsIndexService.deleteIndexing(goodsID);
                    } else {
                        goodsIndexService.updateIndexingSelective(index);
                    }
                    return true;
                case 4:
                    //回滚库存 减少销量
                    if (goodsInfoMapper.opeateInventoryOrSales(-number, number, goodsID) == 0) {
                        throw CommonTools.createException(ErrorCodeEnum.goodsInventoryShortage);
                    }

                    //更新商品索引 销量信息
                    GoodsInfo goodsInfo1 = goodsInfoMapper.selectByPrimaryKey(goodsID);
                    GoodsIndexInfoVo index1 = new GoodsIndexInfoVo();
                    index1.setGoodsID(goodsID);
                    index1.setSalas(goodsInfo1.getSales());
                    if (goodsInfo1.getInventory() == 0) {
                        goodsIndexService.deleteIndexing(goodsID);
                    } else {
                        goodsIndexService.updateIndexingSelective(index1);
                    }
                    return true;
                default:
                    return false;
            }
            return true;
        } catch (ServiceException se) {
            throw se;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw CommonTools.createException(ErrorCodeEnum.synchronizationInventoryFailure);
        }
    }

    @Transactional
    public boolean changeInventory(int operateType, Long goodsID, Long skuID, int number) {
        switch (operateType) {
            case 1:
                //减good库存
                if (goodsInfoMapper.opeateInventoryOrSales(null, -number, goodsID) == 0) {
                    throw CommonTools.createException(ErrorCodeEnum.goodsInventoryShortage);
                }
                break;
            case 2:
                //借货审核拒绝+sku库存
                if (goodsSkuMapper.addInventoryBySkuID(skuID, number) == 0) {
                    throw CommonTools.createException(ErrorCodeEnum.synchronizationInventoryFailure);
                }
                break;
            case 3:
                //+sku,good库存
                if (goodsSkuMapper.addInventoryBySkuID(skuID, number) == 0) {
                    throw CommonTools.createException(ErrorCodeEnum.synchronizationInventoryFailure);
                }
                if (goodsInfoMapper.opeateInventoryOrSales(null, number, goodsID) == 0) {
                    throw CommonTools.createException(ErrorCodeEnum.goodsInventoryShortage);
                }
                break;

        }
        return true;
    }

    /**
     * 获取 供应商户商品统计信息
     *
     * @param supplierID
     * @param needRank   0 不需要，1 需要
     * @return
     */
    public GoodsCountInfoDto queryGoodsCountData(Long supplierID, int needRank) {
        GoodsCountInfoDto count = goodsInfoMapper.selectCountGoodsDataBySupplierID(supplierID, SystemContext.getCompanyID());
        if (needRank == 1) {
            count.setGoodsSalesRank(goodsInfoMapper.selectGoodsRankBySales(supplierID, 5, SystemContext.getCompanyID()));
        }
        return count;
    }

    /**
     * 获取 供应商户商品统计信息
     *
     * @param supplierID
     * @param needRank   0 不需要，1 需要
     * @return
     */
    public GoodsCountInfoDto queryGoodsCountData(Long supplierID, int needRank, int topNum) {
        GoodsCountInfoDto count = goodsInfoMapper.selectCountGoodsDataBySupplierID(supplierID, SystemContext.getCompanyID());
        if (needRank == 1) {
            count.setGoodsSalesRank(goodsInfoMapper.selectGoodsRankBySales(supplierID, topNum - 1, SystemContext.getCompanyID()));
        }
        return count;
    }

    /**
     * 查询供应商在售商品数量top10
     *
     * @param topNum
     * @return
     */
    public Object queryGoodsTop(int topNum) {
        return goodsInfoMapper.selectGoodsTop(topNum - 1, SystemContext.getCompanyID());
    }

    /**
     * 获取 供应商户商品统计信息
     *
     * @param supplierID
     * @return
     */
    public Object queryGoodsSalesRank(Long supplierID, int topNum) {
        return goodsInfoMapper.selectGoodsRankBySales(supplierID, topNum - 1, SystemContext.getCompanyID());
    }

    public Object querySupplierRank() {
        Map<Object, Object> ranks = new HashMap<Object, Object>();
        GoodsCountInfoDto count = this.queryGoodsCountData(null, 1, 10);
        ranks.put("salesRank", count.getGoodsSalesRank());
        ranks.put("goodsRank", this.queryGoodsTop(10));
        ranks.put("goodsCount", count.getGoodsNum());
        return ranks;
    }

    /**
     * 查询商品-价格 集合
     *
     * @param goodsIDs
     * @return
     */
    public Object queryMultipleGoodsPrice(List<Long> goodsIDs, Long userID) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (goodsIDs.size() == 0) {
            return resultMap;
        }
        Long VipPriceSW = getVipPriceSW(SystemContext.getCompanyID());
        List<Map<String, Object>> results = new ArrayList<>();
        if (2l == VipPriceSW && null != userID && !getIsBocgold()) {//会员价开启
            UserInfoForOrderDto userInfoForOrderDto = (UserInfoForOrderDto) getUserInfoForOrder(userID);
            results = goodsInfoMapper.selectMultipleGoodsPriceV2(goodsIDs, userInfoForOrderDto.getVipLevel());
        } else {
            results = goodsInfoMapper.selectMultipleGoodsPrice(goodsIDs);
        }

        for (Map<String, Object> map : results) {
            resultMap.put(map.get("goodsID").toString(), map.get("price"));
        }
        return resultMap;
    }

    public Map<String, Object> queryUnapproveGoodsNum(String supplierID, Long companyID) {
        return goodsInfoMapper.selectUnapproveGoodsNum(supplierID, companyID);
    }

    /***************************************************************
     * ******************private method******************************
     * **************************************************************/

    /**
     * 远程获取入驻商信息
     *
     * @param supplierID
     * @return
     */
    private SupperlierInfoVo remoteGetSupplierInfo(Long supplierID) {
        DataResult result = HttpUtil.httpGet(ProConstants.BASE + "/company/base/" + supplierID, restTemplate);
        if (result.getIsSuccess() == 0 || result.getData() == null) {
            throw CommonTools.createException(ErrorCodeEnum.RemoteGetSupplierInfoFailure);
        }
        Map<String, Object> sinfo = (Map<String, Object>) result.getData();
        SupperlierInfoVo info = new SupperlierInfoVo();
        info.setContacts(sinfo.containsKey("contacts") ? sinfo.get("contacts") : null);
        info.setMobile(sinfo.containsKey("contactPhone") ? sinfo.get("contactPhone") : null);
        info.setTelephone(sinfo.containsKey("telephone") ? sinfo.get("telephone") : null);
        info.setSupplierName(sinfo.containsKey("companyName") ? sinfo.get("companyName") : null);
        return info;
    }


    /**
     * 比较价格
     *
     * @param flag   1返回最大值，0返回最小值
     * @param souce
     * @param target
     * @return
     */
    private BigDecimal comparePrice(int flag, BigDecimal souce, BigDecimal target) {
        switch (flag) {
            case 0:
                if (souce.compareTo(new BigDecimal("-1")) == 0) {
                    return target;
                } else if (souce.compareTo(target) == 1) {
                    return souce;
                } else {
                    return target;
                }
            default:
                if (souce.compareTo(target) == 1) {
                    return target;
                } else {
                    return souce;
                }
        }
    }

    /**
     * 批量更新商品图片
     *
     * @param gi
     * @param imgUrlList 商品图片地址
     */
    private void batchInsertGoodsImages(GoodsInfo gi, List<String> imgUrlList) {
        try {
            //a.删除原来关联的图片
            goodsImagesMapper.deleteByGoodsID(gi.getGoodsID());
            if (imgUrlList == null || imgUrlList.size() == 0) {
                return;
            }
            int index = 0;
            List<GoodsImages> goodsImageList = new ArrayList<GoodsImages>();
            for (String imgUrl : imgUrlList) {
                goodsImageList.add(new GoodsImages(gi.getGoodsID(), imgUrl, index, ""));
                index++;
            }
            // c.批量插入img
            int result = goodsImagesMapper.insertBatch(goodsImageList);
            if (result != goodsImageList.size()) {
                throw CommonTools.createException(ErrorCodeEnum.goodsImageError);
            }
            //设置主图
            gi.setImg(imgUrlList.get(0));
        } catch (Exception e) {
            logger.info(e.getMessage());
            throw CommonTools.createException(ErrorCodeEnum.goodsImageError);
        }
    }

    /**
     * 批量更新商品图片
     *
     * @param gi
     * @param imgUrlList 商品图片地址
     */
    private void batchInsertGoodsImagesV2(GoodsInfo gi, List<GoodsImages> imgUrlList) {
        try {
            //a.删除原来关联的图片
            goodsImagesMapper.deleteByGoodsID(gi.getGoodsID());
            if (imgUrlList == null || imgUrlList.size() == 0) {
                return;
            }
            int index = 0;
            List<GoodsImages> goodsImageList = new ArrayList<GoodsImages>();
            for (GoodsImages imgUrl : imgUrlList) {
                goodsImageList.add(new GoodsImages(gi.getGoodsID(), imgUrl.getUrl(), index, ""));
                index++;
            }
            // c.批量插入img
            int result = goodsImagesMapper.insertBatch(goodsImageList);
            if (result != goodsImageList.size()) {
                throw CommonTools.createException(ErrorCodeEnum.goodsImageError);
            }
            //设置主图
            gi.setImg(imgUrlList.get(0).getUrl());
        } catch (Exception e) {
            logger.info(e.getMessage());
            throw CommonTools.createException(ErrorCodeEnum.goodsImageError);
        }
    }

    /**
     * 批量更新sku信息
     *
     * @param gi
     * @param goodsSkuList
     * @param state        update or insert
     */
    @Transactional
    private void batchInsertGoodsSkuInfo(GoodsInfo gi, List<GoodsSku> goodsSkuList, OperateTypeEnum state) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            if (goodsSkuList == null || goodsSkuList.size() == 0) {
                return;
            }
            BigDecimal lowstPrice = null;//最低价格
            Integer totalInventory = 0;//总库存

            //sku索引
            Map<Integer, Long> skuIndex = new HashMap<Integer, Long>();
            if (OperateTypeEnum.update.equals(state)) {//如果是更新sku
                List<GoodsSku> goodsSKUs = goodsSkuMapper.selectByGoodsID(gi.getGoodsID());
                int index = 0;
                for (GoodsSku skuInfo : goodsSKUs) {
                    skuIndex.put(index++, skuInfo.getSkuID());
                }
            }
            //删除sku信息
            goodsSkuMapper.deleteByGoodsID(gi.getGoodsID());
            goodsAttrStoneMapper.deleteByGoodsID(gi.getGoodsID());
            //根据分类计算代理价格 added by pengzh 2018-3-22
            List<String> classifyList = new ArrayList<String>();
            classifyList.add(gi.getSubClassifyID());
            Integer priceAgentFirst = null;
            Integer priceAgentSec = null;
            Integer priceAgentThir = null;

            GoodsClassifyRebate goodsClassifyRebate = (GoodsClassifyRebate) rebateService.selectListByShopID(gi.getSubClassifyID(), SystemContext.getCompanyID());
            if (goodsClassifyRebate != null) {
                priceAgentFirst = goodsClassifyRebate.getBankVal();
                priceAgentSec = goodsClassifyRebate.getEmployeeVal();
                priceAgentThir = goodsClassifyRebate.getThirdVal();
            }

            //遍历sku新信息
            Integer index = 0;
            for (GoodsSku temp : goodsSkuList) {
                temp.setGoodsID(gi.getGoodsID());//关联商品ID
                if (temp.getInventory() == null) {
                    temp.setInventory(0);
                }
                if (temp.getPrice() == null) {
                    temp.setPrice(new BigDecimal("0"));
                }
                totalInventory += temp.getInventory();//库存累加
                // 得到sku最低价
                if (lowstPrice == null) {
                    // 第一个sku价格赋值给lowstPrice
                    lowstPrice = temp.getPrice();
                } /*else if (lowstPrice.compareTo(temp.getPrice()) == 1) {
                    // 如果当前sku价格低于最低价
                    lowstPrice = temp.getPrice();
                }*/
                //ps最新逻辑 取第一个价格
                if (OperateTypeEnum.insert.equals(state)) {
                    temp.setSkuID(IdGen.get().nextId());
                }
                //删除存在sku索引 得到失效sku 更新购物车
                temp.setSeq(index);//插入排序
                if (skuIndex.containsKey(index)) {
                    temp.setSkuID(skuIndex.get(index));
                    skuIndex.remove(index);
                } else {
                    temp.setSkuID(IdGen.get().nextId());
                }

                //根据分类计算代理价格 added by pengzh 2018-3-22

                //不做存储 gaoqiang 2018-4-6

                /*if (priceAgentFirst != null) {
                    temp.setViphPrice(temp.getPrice().multiply((new BigDecimal(priceAgentFirst)).divide(new BigDecimal(1000))));
                }
                if (priceAgentSec != null) {
                    temp.setVipmPrice(temp.getPrice().multiply((new BigDecimal(priceAgentSec)).divide(new BigDecimal(1000))));
                }
                if (priceAgentThir != null) {
                    temp.setVipsPrice(temp.getPrice().multiply((new BigDecimal(priceAgentThir)).divide(new BigDecimal(1000))));
                }*/
                index++;
            }

            // 批量插入到sku
            int result = goodsSkuMapper.insertBatch(goodsSkuList);
            if (result != goodsSkuList.size()) {
                throw CommonTools.createException(ErrorCodeEnum.goodsSkuNoInventory);
            }

            //判断是否需要高级查询 start
            String highQuery = queryHighQueryClazzID() + "";
            if (CommonUtils.isNotEmpty(highQuery)) {
                String[] highQuerys = highQuery.split(",");
                List<String> stone = Arrays.asList(highQuerys);
                if (stone.contains(gi.getClassifyID())) {
                    List<GoodsSkuExtDto> extDto = new ArrayList<>();
                    for (GoodsSku sku : goodsSkuList) {
                        GoodsSkuExtDto goodsSkuExtDto = new GoodsSkuExtDto();
                        BeanUtils.copyProperties(sku, goodsSkuExtDto);
                        goodsSkuExtDto.setGoodsAttr(gi.getAttr());
                        extDto.add(goodsSkuExtDto);
                    }
                    saveGoodsAttrStone(extDto);
                }
            }

            //判断是否需要高级查询 end

            //通知购物车失效
            if (OperateTypeEnum.update.equals(state) && skuIndex.size() > 0) {
                List<Long> list = new ArrayList<Long>();
                list.addAll(skuIndex.values());
                this.notifyGoodsCartExpire(list, 0);
            }
            gi.setInventory(totalInventory);
            gi.setPrice(lowstPrice);
        } catch (ServiceException se) {
            throw se;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw CommonTools.createException(ErrorCodeEnum.goodsSkuNoInventory);
        }
    }

    public Object queryHighQueryClazzID() {
        try {
            return CommonTools.getExtString(restTemplate, CfgExtEnum.HIGHQUERYCLAZZID.getCode());
        } catch (Exception e) {
            return "";
        }

    }

    public int saveGoodsAttrStone(List<GoodsSkuExtDto> goodsSkuExtList) {
        List<GoodsAttrStone> stones = new ArrayList<>();
        for (GoodsSkuExtDto sku : goodsSkuExtList) {
            GoodsAttrStone stone = new GoodsAttrStone();
            stone.setGoodsID(sku.getGoodsID());
            stone.setStoneID(IdGen.get().nextId());
            stone.setSkuID(sku.getSkuID());
            JSONObject obj = JSONObject.fromObject(sku.getAttrJson());
            String goodsAttr_temp = sku.getGoodsAttr().replace("null,", "");//中间或最前面的null
            logger.info("goodsAttr_temp===" + goodsAttr_temp);
            goodsAttr_temp = goodsAttr_temp.replace("null", "");//最后面的null
            List<JSONObject> goodsJsonList = JsonUtil.toList(goodsAttr_temp);
            logger.info("objAku===" + obj);
            for (JSONObject goodsAttr : goodsJsonList) {
                if (!obj.containsKey(goodsAttr.get("clazzattrcode"))) {
                    obj.put(goodsAttr.get("clazzattrcode"), goodsAttr.get("clazzattrval"));
                }

            }
            logger.info("obj===" + obj);
            stone.setHxCutType(DataUtils.getStr(obj, "hxCutType", null));
            stone.setHxColor(DataUtils.getStr(obj, "hxColor", null));
            stone.setHxShape(DataUtils.getStr(obj, "hxShape", null));
            stone.setHxNeatness(DataUtils.getStr(obj, "hxNeatness", null));
            stone.setHxLucency(DataUtils.getStr(obj, "hxLucency", null));
            stone.setHxCutGrade(DataUtils.getStr(obj, "hxCutGrade", null));
            stone.setHxFireGrade(DataUtils.getStr(obj, "hxFireGrade", null));
            // stone.setHxSize(obj.containsKey("hxSize")?new BigDecimal(obj.get("hxSize").toString()):null);//类型为中英文字符
            stone.setWeight(obj.containsKey("weight") ? new BigDecimal(obj.get("weight").toString().trim()) : null);
            stone.setMsClarity(DataUtils.getStr(obj, "msClarity", null));
            stone.setMsColor(DataUtils.getStr(obj, "msColor", null));
            stone.setMsCut(DataUtils.getStr(obj, "msCut", null));
            stone.setMsWeight(obj.containsKey("msWeight") ? new BigDecimal(obj.get("msWeight").toString().trim()) : null);
            stone.setGGcertNum(DataUtils.getStr(obj, "GGcertNum", null));
            stone.setHxColorGrade(DataUtils.getStr(obj, "hxColorGrade", null));
            stone.setHxStore(DataUtils.getStr(obj, "hxStore", null));
            stone.setHxGradeNO(DataUtils.getStr(obj, "hxGradeNO", null));
            stone.setHxHandleMethod(DataUtils.getStr(obj, "hxHandleMethod", null));
            stone.setHxPolish(DataUtils.getStr(obj, "hxPolish", null));
            stone.setHxSym(DataUtils.getStr(obj, "hxSym", null));
            stone.setHxLight(DataUtils.getStr(obj, "hxLight", null));
            stone.setGGcertOrg(DataUtils.getStr(obj, "GGcertOrg", null));
            stone.setHxBrand(DataUtils.getStr(obj, "hxBrand", null));
            stone.setHxCraft(DataUtils.getStr(obj, "hxCraft", null));
            stone.setHxHandSize(obj.containsKey("hxHandSize") ? new BigDecimal(obj.get("hxHandSize").toString().trim()) : null);
            stone.setHxCertOrg(DataUtils.getStr(obj, "hxCertOrg", null));
            stone.setHxInlay(DataUtils.getStr(obj, "hxInlay", null));

            stones.add(stone);
        }
        return goodsAttrStoneMapper.insertBatch(stones);

    }


    public int saveGoodsAttrStone_old(List<GoodsSkuExtDto> goodsSkuExtList) {
        List<GoodsAttrStone> stones = new ArrayList<>();
        for (GoodsSkuExtDto sku : goodsSkuExtList) {
            GoodsAttrStone stone = new GoodsAttrStone();
            stone.setGoodsID(sku.getGoodsID());
            stone.setStoneID(IdGen.get().nextId());
            stone.setSkuID(sku.getSkuID());
            JSONObject obj = JSONObject.fromObject(sku.getAttrJson());
            String goodsAttr_temp = sku.getGoodsAttr().replace("null", "{}");
            List<JSONObject> goodsJsonList = JsonUtil.toList(goodsAttr_temp);
            logger.info("obj===" + obj);
            System.out.print("obj======" + obj);
            stone.setHxCutType(DataUtils.getStr(obj, "hxCutType", null));
            stone.setHxColor(DataUtils.getStr(obj, "hxColor", null));
            stone.setHxShape(DataUtils.getStr(obj, "hxShape", null));
            stone.setHxNeatness(DataUtils.getStr(obj, "hxNeatness", null));
            stone.setHxLucency(DataUtils.getStr(obj, "hxLucency", null));
            stone.setHxCutGrade(DataUtils.getStr(obj, "hxCutGrade", null));
            stone.setHxFireGrade(DataUtils.getStr(obj, "hxFireGrade", null));
            // stone.setHxSize(obj.containsKey("hxSize")?new BigDecimal(obj.get("hxSize").toString()):null);//类型为中英文字符
            stone.setWeight(obj.containsKey("weight") ? new BigDecimal(obj.get("weight").toString().trim()) : null);
            stone.setMsClarity(DataUtils.getStr(obj, "msClarity", null));
            stone.setMsColor(DataUtils.getStr(obj, "msColor", null));
            stone.setMsCut(DataUtils.getStr(obj, "msCut", null));
            stone.setMsWeight(obj.containsKey("msWeight") ? new BigDecimal(obj.get("msWeight").toString().trim()) : null);
            stone.setGGcertNum(DataUtils.getStr(obj, "GGcertNum", null));
            stone.setHxColorGrade(DataUtils.getStr(obj, "hxColorGrade", null));

            stone.setHxPolish(DataUtils.getStr(obj, "hxPolish", null));
            stone.setHxSym(DataUtils.getStr(obj, "hxSym", null));
            stone.setHxLight(DataUtils.getStr(obj, "hxLight", null));

            stone.setHxHandSize(obj.containsKey("hxHandSize") ? new BigDecimal(obj.get("hxHandSize").toString().trim()) : null);


            for (JSONObject goodsAttr : goodsJsonList) {//商品属性
                System.out.print(goodsAttr);
                if (goodsAttr.size() == 0) {
                    continue;
                }
                if (goodsAttr.get("clazzattrcode").equals("hxStore")) {
                    stone.setHxStore(goodsAttr.get("clazzattrval").toString());
                }
                if (goodsAttr.get("clazzattrcode").equals("hxGradeNO")) {
                    stone.setHxGradeNO(goodsAttr.get("clazzattrval").toString());
                }
                if (goodsAttr.get("clazzattrcode").equals("hxHandleMethod")) {
                    stone.setHxHandleMethod(goodsAttr.get("clazzattrval").toString());
                }
                if (goodsAttr.get("clazzattrcode").equals("GGcertOrg")) {
                    stone.setGGcertOrg(goodsAttr.get("clazzattrval").toString());
                }
                if (goodsAttr.get("clazzattrcode").equals("hxBrand")) {
                    stone.setGGcertOrg(goodsAttr.get("clazzattrval").toString());
                }
                if (goodsAttr.get("clazzattrcode").equals("hxCraft")) {
                    stone.setGGcertOrg(goodsAttr.get("clazzattrval").toString());
                }


                if (goodsAttr.get("clazzattrcode").equals("hxFireGrade")) {
                    stone.setHxFireGrade(goodsAttr.get("clazzattrval").toString());
                }
                if (goodsAttr.get("clazzattrcode").equals("hxNeatness")) {
                    stone.setHxNeatness(goodsAttr.get("clazzattrval").toString());
                }
                if (goodsAttr.get("clazzattrcode").equals("hxCutGrade")) {
                    stone.setHxCutGrade(goodsAttr.get("clazzattrval").toString());
                }
                if (goodsAttr.get("clazzattrcode").equals("msWeight")) {
                    stone.setMsWeight(CommonUtils.isNotEmpty(goodsAttr.get("clazzattrval").toString()) ? new BigDecimal(goodsAttr.get("clazzattrval").toString().trim()) : null);
                }
                if (goodsAttr.get("clazzattrcode").equals("hxLucency")) {
                    stone.setHxLucency(goodsAttr.get("clazzattrval").toString());
                }
                if (goodsAttr.get("clazzattrcode").equals("hxShape")) {
                    stone.setHxShape(goodsAttr.get("clazzattrval").toString());
                }
                if (goodsAttr.get("clazzattrcode").equals("hxCutType")) {
                    stone.setHxCutType(goodsAttr.get("clazzattrval").toString());
                }
                if (goodsAttr.get("clazzattrcode").equals("GGcertNum")) {
                    stone.setGGcertNum(goodsAttr.get("clazzattrval").toString());
                }

                if (goodsAttr.get("clazzattrcode").equals("hxHandSize")) {
                    stone.setHxHandSize(CommonUtils.isNotEmpty(goodsAttr.get("clazzattrval").toString()) ? new BigDecimal(goodsAttr.get("clazzattrval").toString().trim()) : null);
                }

                if (goodsAttr.get("clazzattrcode").equals("hxCertOrg")) {
                    stone.setHxCertOrg(goodsAttr.get("clazzattrval").toString());
                }
                if (goodsAttr.get("clazzattrcode").equals("hxInlay")) {
                    stone.setHxInlay(goodsAttr.get("clazzattrval").toString());
                }
            }

            stones.add(stone);
        }
        return goodsAttrStoneMapper.insertBatch(stones);
    }


    /**
     * 批量更新sku信息
     *
     * @param gi
     * @param goodsSkuList
     * @param state        update or insert
     */
    @Transactional
    private void batchInsertShopGoodsSkuInfo(GoodsInfo gi, List<GoodsSku> goodsSkuList, OperateTypeEnum state) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            if (goodsSkuList == null || goodsSkuList.size() == 0) {
                return;
            }
            BigDecimal lowstPrice = null;//最低价格
            Integer totalInventory = 0;//总库存


            //遍历sku新信息
            Integer index = 0;

            List<GoodsSkuShop> skuShopList = new ArrayList<GoodsSkuShop>();

            for (GoodsSku temp : goodsSkuList) {
                temp.setGoodsID(gi.getGoodsID());//关联商品ID
                if (temp.getPrice() == null) {
                    temp.setPrice(new BigDecimal("0"));
                }
                // 得到sku最低价
                if (lowstPrice == null) {
                    // 第一个sku价格赋值给lowstPrice
                    lowstPrice = temp.getPrice();
                }/* else if (lowstPrice.compareTo(temp.getPrice()) == 1) {
                    // 如果当前sku价格低于最低价
                    lowstPrice = temp.getPrice();
                }*/

                GoodsSkuShop skuShop = new GoodsSkuShop();
                skuShop.setSkuShopID(IdGen.get().nextId());
                skuShop.setGoodsID(temp.getGoodsID());
                skuShop.setShopID(gi.getShopID());
                skuShop.setSkuID(temp.getSkuID());
                if (gi.getPriceType() == 0) {
                    skuShop.setPrice(temp.getPrice());
                } else {
                    skuShop.setPrice(BigDecimal.ZERO);
                    skuShop.setOtherFee(temp.getPrice());
                }


                skuShopList.add(skuShop);
            }
            goodsSkuShopMapper.insertBatch(skuShopList);

            gi.setPrice(lowstPrice);
        } catch (ServiceException se) {
            throw se;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw CommonTools.createException(ErrorCodeEnum.goodsSkuNoInventory);
        }
    }

    /**
     * 更新商品主信息
     *
     * @param gi
     * @param state update or insert
     */
    private void operateGoodsInfo(GoodsInfoWithBLOBs gi, OperateTypeEnum state) {
        int result = 0;
        if (OperateTypeEnum.update.equals(state)) {
            result = goodsInfoMapper.updateByPrimaryKeySelective(gi);
            if (result != 1) {
                throw CommonTools.createException(ErrorCodeEnum.operateGoodsInfoFailure);
            }
            goodsInfoMapper.updateBySoldoutTime(gi.getGoodsID());
            //删除索引
            goodsIndexService.deleteIndexing(gi.getGoodsID());
            updateVal2(gi);
        } else {
            gi.setCompanyID(SystemContext.getCompanyID());//赋值公司ID
            result = goodsInfoMapper.insertSelective(gi);
            if (result != 1) {
                throw CommonTools.createException(ErrorCodeEnum.operateGoodsInfoFailure);
            }
            updateVal(gi);
        }

    }

    /**
     * 操作购物车的失效状态
     *
     * @param goodsID
     * @param state   0 失效 1正常
     * @return
     */
    private int notifyGoodsCartExpire(Long goodsID, Integer state) {
        //通知购物车中该商品下架
        List<Long> list = new ArrayList<Long>();
        list.add(goodsID);
        return goodsCartMapper.updateCartStateByGoodsID(list, state);
    }

    private int notifyGoodsCartExpireByShop(Long goodsID, Long shopID, Integer state) {
        //通知购物车中该商品下架
        List<Long> list = new ArrayList<Long>();
        list.add(goodsID);
        return goodsCartMapper.updateCartStateByGoodsIDAndShopID(list, shopID, state);
    }

    /**
     * 操作购物车的失效状态
     *
     * @param goodsIDs
     * @param state    0 失效 1正常
     * @return
     */
    private int notifyGoodsCartExpire(List<Long> goodsIDs, Integer state) {
        //通知购物车中该商品下架
        return goodsCartMapper.updateCartStateByGoodsID(goodsIDs, state);
    }

    /**
     * 根据款号加载
     *
     * @param proNo
     * @return
     */
    public Long selectByPrdNo(String proNo) {
        return goodsInfoMapper.selectByPrdNo(proNo, SystemContext.getCompanyID());
    }

    /**
     * 商品状态
     *
     * @param skuID
     * @return
     */
    public String retState(Long skuID) {
        GoodsInfoWithSkuDto dto = goodsInfoMapper.selectBySkuID(skuID);
        return dto.getState();
    }

    /**
     * 获取会员价开关
     *
     * @param companyID
     * @return
     */
    private Long getVipPriceSW(Long companyID) {
        DataResult result = HttpUtil.httpGet(
                ProConstants.getVipPriceSW + companyID, restTemplate);
        return result.getIsSuccess() == 1 ? Long.valueOf(result.getData().toString()) : 0l;
    }

    //获取下订单需要的UserInfo及其组织信息
    private Object getUserInfoForOrder(Long userID) {
        JSONObject jsonObject = HttpUtil.httpGetJSONObject(ProConstants.getUserInfoForOrder + userID, restTemplate);
        //if (jsonObject.get("isSuccess") != 1) {
        if (!com.google.common.base.Objects.equal(DataUtils.getInteger(jsonObject, "isSuccess"), 1)) {
            throw new ServiceException("调用base服务获取用户信息接口出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        return (UserInfoForOrderDto) JSONObject.toBean(jsonObject.getJSONObject("data"), UserInfoForOrderDto.class);
    }


    public Object getPlatformAttrList(ClazzObjDto list) {
        String classifyType = CommonTools.getExtString(restTemplate, "classifyType");
        list.setPlatform(Integer.parseInt(classifyType));
        DataResult result = rest.postForObject(classifyAttrUrl, list, DataResult.class);

        if (result.getIsSuccess() != 1) {
            throw new ServiceException("调用云管控服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }else{
            Object data=result.getData();
            JSONObject jsonObject=JSONObject.fromObject(data);
            List listatr=(List)jsonObject.get("goodsAttrList");
            System.out.println(listatr.size());
        }
        return result.getData();

    }


    /**
     * 云管控获取本系统的分类列表，合并出品类的使用情况
     *
     * @return
     */
    public List<JSONObject> getPlatformClassList(Long shopID) {
        JSONObject jsonObject = rest.getForObject(classifyUrl + CommonTools.getExtString(restTemplate, "classifyType"), JSONObject.class);
        logger.info("jsonObject=" + jsonObject.toString());

        if (jsonObject.getInt("isSuccess") != 1) {
            throw new ServiceException("调用云管控服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        List<JSONObject> objectList = jsonObject.getJSONArray("data");
        if (shopID != null) { //店铺大分类过滤
            List<ClassifyShop> classifyShops = classifyShopMapper.selectByShopID(shopID);
            List<JSONObject> newObjectList = new ArrayList<>();
            for (JSONObject classify : objectList) {
                for (ClassifyShop classifyShop : classifyShops) {
                    if (Objects.equal(classifyShop.getClazzID(), classify.get("clazzid") + "")) {
                        newObjectList.add(classify);
                    }
                }
            }
            objectList = newObjectList;
        }

        if (objectList.isEmpty() || objectList.size() == 0) {
            return objectList;
        }


        List<String> classifyList = new ArrayList<String>();
        for (JSONObject jsonObject1 : objectList) {
            classifyList.add(jsonObject1.get("clazzid") + "");
        }


        Map<String, Object> resultMap = (Map<String, Object>) goodsClassifyCommissionService.selectByClazzIDList(classifyList);
        for (JSONObject jsonClazz : objectList) {
            if (resultMap != null && resultMap.containsKey(jsonClazz.get("clazzid") + "") && resultMap.get(jsonClazz.get("clazzid") + "") != null) {
                jsonClazz.put("clazzVal", resultMap.get(jsonClazz.get("clazzid") + ""));
            } else {
                jsonClazz.put("clazzVal", new JSONObject());
            }

            if (jsonClazz.containsKey("clazzcode") && StringUtils.isEmpty(jsonClazz.getString("clazzcode"))) {
                jsonClazz.put("clazzcode", "");
            }
        }
        return objectList;
    }


    public List<Map<String, Object>> clazzListPull(Long shopID) {
        //System.out.println(classifyUrl+",,,,,,,clazzListPull");
        JSONObject jsonObject = rest.getForObject(classifyUrl + CommonTools.getExtString(restTemplate, "classifyType"), JSONObject.class);
        if (jsonObject.getInt("isSuccess") != 1) {
            throw new ServiceException("调用云管控服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        List<JSONObject> objectList = jsonObject.getJSONArray("data");
        List<Map<String, Object>> classifyList = new ArrayList<Map<String, Object>>();

        if (shopID != null) { //店铺大分类过滤
            List<ClassifyShop> classifyShops = classifyShopMapper.selectByShopID(shopID);
            List<JSONObject> newObjectList = new ArrayList<>();
            for (JSONObject classify : objectList) {
                for (ClassifyShop classifyShop : classifyShops) {
                    if (Objects.equal(classifyShop.getClazzID(), classify.get("clazzid") + "")) {
                        newObjectList.add(classify);
                    }
                }
            }
            objectList = newObjectList;
        }

        for (JSONObject jsonObject1 : objectList) {
            Map<String, Object> map = new HashMap<>();
            map.put("clazzid", jsonObject1.get("clazzid") + "");
            map.put("clazzname", jsonObject1.get("clazzname") + "");
            classifyList.add(map);
        }
        return classifyList;
    }


    /**
     * @param clazzId 上级分类ID
     * @return
     * @Author Tim Peng
     * @Description
     * @Date 2018/6/26 10:43
     */
    public List<Map<String, Object>> getClassifyListPullById(String clazzId) {
        if (CommonUtils.isEmpty(clazzId)) {
            return null;
        }
        JSONObject jsonObject = rest.getForObject(classifySearchByIdUrl + clazzId, JSONObject.class);
        if (jsonObject.getInt("isSuccess") != 1) {
            throw new ServiceException("调用云管控服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        List<JSONObject> objectList = jsonObject.getJSONArray("data");
        List<Map<String, Object>> classifyList = new ArrayList<Map<String, Object>>();

        for (JSONObject jsonObject1 : objectList) {
            Map<String, Object> map = new HashMap<>();
            map.put("clazzid", jsonObject1.get("clazzid") + "");
            map.put("clazzname", jsonObject1.get("clazzname") + "");
            classifyList.add(map);
        }
        return classifyList;
    }


    public List<JSONObject> getClassList(Long sellerID) {
        //获取一级
        JSONObject jsonObject = rest.getForObject(classifyUrl + CommonTools.getExtString(restTemplate, "classifyType"), JSONObject.class);
        if (jsonObject.getInt("isSuccess") != 1) {
            throw new ServiceException("调用云管控服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        List<JSONObject> objectList = jsonObject.getJSONArray("data");
        //List<JSONObject> objectList1 = new ArrayList<>();
        List<String> classifyList = new ArrayList<String>();
        //读取云管控一级分类
        for (JSONObject jsonObject1 : objectList) {
            classifyList.add(jsonObject1.get("clazzid") + "");
        }
        Map<String, Object> resultMap = (Map<String, Object>) rebateService.selectByClazzIDList(classifyList, sellerID);
        for (JSONObject jsonClazz : objectList) {
            if (resultMap != null && resultMap.containsKey(jsonClazz.get("clazzid") + "")
                    && resultMap.get(jsonClazz.get("clazzid") + "") != null) {
                jsonClazz.put("clazzVal", resultMap.get(jsonClazz.get("clazzid") + ""));
            } else {
                jsonClazz.put("clazzVal", "");
            }
            if (jsonClazz.containsKey("clazzcode") && StringUtils.isEmpty(jsonClazz.getString("clazzcode"))) {
                jsonClazz.put("clazzcode", "");
            }
        }
        return objectList;
    }

    /**
     * 云管控按品类查子类
     *
     * @return
     */
    public List<JSONObject> getClassifyListById(String clazzId) {
        if (CommonUtils.isEmpty(clazzId)) {
            return null;
        }
        JSONObject jsonObject = rest.getForObject(classifySearchByIdUrl + clazzId, JSONObject.class);
        if (jsonObject.getInt("isSuccess") != 1) {
            throw new ServiceException("调用云管控服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        List<JSONObject> objectList = jsonObject.getJSONArray("data");
        List<String> classifyList = new ArrayList<String>();

        for (JSONObject jsonObject1 : objectList) {
            classifyList.add(jsonObject1.get("clazzid") + "");
        }
        if (objectList.isEmpty()) {
            return objectList;
        }
        Map<String, Object> resultMap = (Map<String, Object>) goodsClassifyCommissionService.selectByClazzIDList(classifyList);
        for (JSONObject jsonClazz : objectList) {
            if (resultMap != null && resultMap.containsKey(jsonClazz.get("clazzid") + "") && resultMap.get(jsonClazz.get("clazzid") + "") != null) {
                jsonClazz.put("clazzVal", resultMap.get(jsonClazz.get("clazzid") + ""));
            } else {
                jsonClazz.put("clazzVal", "");
            }
            if (jsonClazz.containsKey("clazzcode") && StringUtils.isEmpty(jsonClazz.getString("clazzcode"))) {
                jsonClazz.put("clazzcode", "");
            }
        }
        return objectList;
    }


    /**
     * 云管控按品类查子类
     *
     * @return
     */
    public List<JSONObject> getClassifyListByIdV2(String clazzId) {
        if (CommonUtils.isEmpty(clazzId)) {
            return null;
        }
        JSONObject jsonObject = rest.getForObject(classifySearchByIdUrl + clazzId, JSONObject.class);
        if (jsonObject.getInt("isSuccess") != 1) {
            throw new ServiceException("调用云管控服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        List<JSONObject> objectList = jsonObject.getJSONArray("data");
        List<String> classifyList = new ArrayList<String>();

        for (JSONObject jsonObject1 : objectList) {
            classifyList.add(jsonObject1.get("clazzid") + "");
        }
        if (objectList.isEmpty()) {
            return objectList;
        }
        Map<String, Object> resultMap = (Map<String, Object>) goodsClassifyCommissionService.selectByClazzIDList(classifyList);
        for (JSONObject jsonClazz : objectList) {
            if (resultMap != null && resultMap.containsKey(jsonClazz.get("clazzid") + "") && resultMap.get(jsonClazz.get("clazzid") + "") != null) {
                jsonClazz.put("clazzVal", resultMap.get(jsonClazz.get("clazzid") + ""));
            } else {
                jsonClazz.put("clazzVal", "");
            }
            if (jsonClazz.containsKey("clazzcode") && StringUtils.isEmpty(jsonClazz.getString("clazzcode"))) {
                jsonClazz.put("clazzcode", "");
            }
        }

        List<ClassifyTag> tagList = classifyTagMapper.selectListByClazzIdShopId(clazzId, SystemContext.getCompanyID());
        for (ClassifyTag classifyTag : tagList) {
            Map<String, Object> tagMap = new HashMap<String, Object>();
            tagMap.put("clazzImage", classifyTag.getImg());

            JSONObject jsonTag = new JSONObject();
            jsonTag.put("clazzcode", classifyTag.getTagCode());////分组code
            jsonTag.put("clazzCodeName", classifyTag.getTagMemo()); //分组名称
            jsonTag.put("clazzname", classifyTag.getTagName());
            jsonTag.put("clazzid", classifyTag.getClazzTagID());
            jsonTag.put("other1", classifyTag.getTagType());//分组类型: 1:tag;2:shape;3:color
            jsonTag.put("clazzremark", "clazzTag");

            jsonTag.put("clazzVal", tagMap);

            objectList.add(jsonTag);
        }
        return objectList;
    }


    //copy by wanglq
    public Object getClassifyListById(String clazzId, Long sellerID) {
        if (CommonUtils.isEmpty(clazzId)) {
            return null;
        }
        JSONObject jsonObject = rest.getForObject(classifySearchByIdUrl + clazzId, JSONObject.class);
        if (jsonObject.getInt("isSuccess") != 1) {
            throw new ServiceException("调用云管控服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        List<JSONObject> objectList = jsonObject.getJSONArray("data");
        List<String> classifyList = new ArrayList<String>();

        for (JSONObject jsonObject1 : objectList) {
            classifyList.add(jsonObject1.get("clazzid") + "");
        }
        Map<String, Object> resultMap = (Map<String, Object>) rebateService.selectByClazzIDList(classifyList, sellerID);
        for (JSONObject jsonClazz : objectList) {
            if (resultMap != null && resultMap.containsKey(jsonClazz.get("clazzid") + "") && resultMap.get(jsonClazz.get("clazzid") + "") != null) {
                jsonClazz.put("clazzVal", resultMap.get(jsonClazz.get("clazzid") + ""));
            } else {
                jsonClazz.put("clazzVal", "");
            }
            if (jsonClazz.containsKey("clazzcode") && StringUtils.isEmpty(jsonClazz.getString("clazzcode"))) {
                jsonClazz.put("clazzcode", "");
            }
        }
        return objectList;
    }

    public List<JSONObject> getClassList2(Long sellerID) {
        //获取一级
        JSONObject jsonObject = rest.getForObject(classifyUrl + CommonTools.getExtString(restTemplate, "classifyType"), JSONObject.class);
        if (jsonObject.getInt("isSuccess") != 1) {
            throw new ServiceException("调用云管控服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        List<JSONObject> objectList = jsonObject.getJSONArray("data");
        List<JSONObject> objectList1 = new ArrayList<>();
        List<String> classifyList = new ArrayList<String>();
        //读取云管控一级分类
        for (JSONObject jsonObject1 : objectList) {
            String clazzId = jsonObject1.get("clazzid") + "";
            if (StringUtils.isNotEmpty(clazzId)) {
                JSONObject jsonObject2 = rest.getForObject(classifySearchByIdUrl + clazzId, JSONObject.class);
                if (jsonObject.getInt("isSuccess") != 1) {
                    throw new ServiceException("调用云管控服务出错", RestConst.ErrorCode.SERVICE_FAIL);
                }
                if (jsonObject2.getJSONArray("data") != null && jsonObject2.getJSONArray("data").size() != 0) {
                    objectList1.addAll(jsonObject2.getJSONArray("data"));
                    for (JSONObject jsonObject3 : objectList1) {
                        classifyList.add(jsonObject3.get("clazzid") + "");
                    }
                }
            }
        }
        Map<String, Object> resultMap = (Map<String, Object>) rebateService.selectByClazzIDList(classifyList, sellerID);
        for (JSONObject jsonClazz : objectList1) {
            if (resultMap != null && resultMap.containsKey(jsonClazz.get("clazzid") + "") && resultMap.get(jsonClazz.get("clazzid") + "") != null) {
                jsonClazz.put("clazzVal", resultMap.get(jsonClazz.get("clazzid") + ""));
            } else {
                jsonClazz.put("clazzVal", "");
            }
            if (jsonClazz.containsKey("clazzcode") && StringUtils.isEmpty(jsonClazz.getString("clazzcode"))) {
                jsonClazz.put("clazzcode", "");
            }
        }
        return objectList1;
    }

    /**
     * 云管控获取本系统的分类查询2级并出品类
     * TODO 中收分类获取
     *
     * @return
     */
    public Object getPlatformClassListLevel2() {
        //获取一级
        JSONObject jsonObject = rest.getForObject(classifyUrl + CommonTools.getExtString(restTemplate, "classifyType"), JSONObject.class);
        if (jsonObject.getInt("isSuccess") != 1) {
            throw new ServiceException("调用云管控服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        List<JSONObject> objectList = jsonObject.getJSONArray("data");
        List<JSONObject> objectList1 = new ArrayList<>();
        List<String> classifyList = new ArrayList<String>();
        //读取云管控一级分类
        for (JSONObject jsonObject1 : objectList) {
            String clazzId = jsonObject1.get("clazzid") + "";
            if (StringUtils.isNotEmpty(clazzId)) {

                JSONObject jsonObject2 = rest.getForObject(classifySearchByIdUrl + clazzId, JSONObject.class);
                if (jsonObject.getInt("isSuccess") != 1) {
                    throw new ServiceException("调用云管控服务出错", RestConst.ErrorCode.SERVICE_FAIL);
                }
                if (jsonObject2.getJSONArray("data") != null && jsonObject2.getJSONArray("data").size() != 0) {
                    objectList1.addAll(jsonObject2.getJSONArray("data"));
                    for (JSONObject jsonObject3 : objectList1) {
                        classifyList.add(jsonObject3.get("clazzid") + "");
                    }
                }
            }
        }
        Map<String, Object> resultMap = (Map<String, Object>) goodsClassifyCommissionService.selectByClazzIDList(classifyList);
        for (JSONObject jsonClazz : objectList1) {
            if (resultMap != null && resultMap.containsKey(jsonClazz.get("clazzid") + "") && resultMap.get(jsonClazz.get("clazzid") + "") != null) {
                jsonClazz.put("clazzVal", resultMap.get(jsonClazz.get("clazzid") + ""));
            } else {
                Map<String, Object> map = (Map<String, Object>) goodsClassifyCommissionService.insertClassifyValByClazzID(jsonClazz.get("clazzid") + "");
                jsonClazz.put("clazzVal", map.get(jsonClazz.get("clazzid") + ""));
            }
            if (jsonClazz.containsKey("clazzcode") && StringUtils.isEmpty(jsonClazz.getString("clazzcode"))) {
                jsonClazz.put("clazzcode", "");
            }
        }
        return objectList1;
    }

    /**
     * 折扣计算
     * 商品查询会员价和代理商价格
     *
     * @param userIDGoodsByDto
     * @return
     */
    public Object goodsDiscountRate(UserIDGoodsByDto userIDGoodsByDto, boolean isb2b) {
        DataResult dataResult = HttpUtil.httpGet(ProConstants.getUserByID + "userType/" + userIDGoodsByDto.getUserID(), restTemplate);
        if (dataResult.getIsSuccess() == 0) {
            logger.info("调用base服务查询adminID失败");
            return null;
        } else {
            JSONObject js = JSONObject.fromObject(dataResult.getData());
            //根据skuIDs查询折扣列表

            List<QueryGoodsSkuRateDto> list = new ArrayList<>();
            if (isb2b) {
                list = selectGoodsSkuRateBySkus(userIDGoodsByDto.getSkuIDS());
            } else {
                //TODO 暂时为了测试通过 前端需调整
                //list= selectGoodsSkuRateBySkus(userIDGoodsByDto.getSkuIDS());
                list = selectGoodsSkuRateBySkus2(userIDGoodsByDto.getSkuIDS(), userIDGoodsByDto.getShopID());
            }


            for (QueryGoodsSkuRateDto queryGoodsSkuRateDto : list) {
                GoodsSku goodsSku = goodsSkuMapper.selectByPrimaryKey(queryGoodsSkuRateDto.getSkuID());
                GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(goodsSku.getGoodsID());
                queryGoodsSkuRateDto.setPriceType(goodsInfo.getPriceType());
                //实时金价商品
                if (goodsInfo.getPriceType() == 1) {
                    if (isb2b) {
                        queryGoodsSkuRateDto.setWholeSalePrice(getTodayGoldPrice(goodsInfo.getSupplierID(), goodsInfo.getAttr(), goodsSku.getAttrJson()));
                        queryGoodsSkuRateDto.setPrice(getTodayGoldPriceByOtherFee(goodsInfo.getSupplierID(), goodsInfo.getAttr(), goodsSku.getAttrJson(), goodsSku.getPrice()));
                    } else {
                        GoodsSkuShop skuShop = goodsSkuShopMapper.selectBySkuIDAndShopID(queryGoodsSkuRateDto.getSkuID(), userIDGoodsByDto.getShopID());
                        queryGoodsSkuRateDto.setPrice(getTodayGoldPriceByOtherFee(goodsInfo.getSupplierID(), goodsInfo.getAttr(), goodsSku.getAttrJson(), skuShop.getOtherFee()));
                    }

                }
            }

            //会员级别;1普通2中级3高级
            if (js != null && js.containsKey("vipLevel")
                    && js.getInt("vipLevel") != 1) {
                Integer vipLevel = js.getInt("vipLevel");

                //List<QueryGoodsSkuRateDto> list = goodsSkuMapper.selectGoodsSkuRate(userIDGoodsByDto.getSkuIDS());
                //modify by wanglq for solve one skuID return Multiple records
                for (QueryGoodsSkuRateDto queryGoodsSkuRateDto : list) {
                    if (vipLevel == 2) {
                        queryGoodsSkuRateDto.setDiscountRate(null);
                        queryGoodsSkuRateDto.setViphPrice(null);
                        queryGoodsSkuRateDto.setCommissionRate(null);
                        queryGoodsSkuRateDto.setVipPrice(queryGoodsSkuRateDto.getVipmPrice());
                    } else if (vipLevel == 3) {
                        queryGoodsSkuRateDto.setDiscountRate(null);
                        queryGoodsSkuRateDto.setCommissionRate(null);
                        queryGoodsSkuRateDto.setVipPrice(queryGoodsSkuRateDto.getViphPrice());
                    } else {
                        queryGoodsSkuRateDto.setCommissionRate(null);
                        queryGoodsSkuRateDto.setDiscountRate(null);
                        queryGoodsSkuRateDto.setVipmPrice(null);
                        queryGoodsSkuRateDto.setViphPrice(null);
                    }
                }
                return list;
            }

            int userGrade = classifyDiscountService.getUserGrade(userIDGoodsByDto.getUserID());//用户等级  1一级代理  2二级代理  3三级代理  9其它
            if (js != null && isb2b) {
                logger.info("=====代理商折扣=========");
                for (QueryGoodsSkuRateDto queryGoodsSkuRateDto : list) {
                    queryGoodsSkuRateDto.setRealPrice(queryGoodsSkuRateDto.getPrice());
                    if (Objects.equal(1, userGrade)) {
                        queryGoodsSkuRateDto.setDiscountRate(queryGoodsSkuRateDto.getViphPrice().divide(new BigDecimal(10)) + "");
                        if (queryGoodsSkuRateDto.getPriceType() == 1) {
                            queryGoodsSkuRateDto.setRealPrice(queryGoodsSkuRateDto.getWholeSalePrice().add(getAgencyAdd(queryGoodsSkuRateDto.getSkuAttrJson(), queryGoodsSkuRateDto.getViphPrice().intValue())).setScale(2, BigDecimal.ROUND_HALF_UP));
                        } else {
                            queryGoodsSkuRateDto.setRealPrice(queryGoodsSkuRateDto.getWholeSalePrice().add(queryGoodsSkuRateDto.getWholeSalePrice().multiply(queryGoodsSkuRateDto.getViphPrice().divide(new BigDecimal(1000)))).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                    } else if (Objects.equal(2, userGrade)) {
                        queryGoodsSkuRateDto.setDiscountRate(queryGoodsSkuRateDto.getVipmPrice().divide(new BigDecimal(10)) + "");
                        if (queryGoodsSkuRateDto.getPriceType() == 1) {
                            queryGoodsSkuRateDto.setRealPrice(queryGoodsSkuRateDto.getWholeSalePrice().add(getAgencyAdd(queryGoodsSkuRateDto.getSkuAttrJson(), queryGoodsSkuRateDto.getVipmPrice().intValue())).setScale(2, BigDecimal.ROUND_HALF_UP));
                        } else {
                            queryGoodsSkuRateDto.setRealPrice(queryGoodsSkuRateDto.getWholeSalePrice().add(queryGoodsSkuRateDto.getWholeSalePrice().multiply(queryGoodsSkuRateDto.getVipmPrice().divide(new BigDecimal(1000)))).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                    } else if (Objects.equal(3, userGrade)) {
                        queryGoodsSkuRateDto.setDiscountRate(queryGoodsSkuRateDto.getVipsPrice().divide(new BigDecimal(10)) + "");
                        if (queryGoodsSkuRateDto.getPriceType() == 1) {
                            queryGoodsSkuRateDto.setRealPrice(queryGoodsSkuRateDto.getWholeSalePrice().add(getAgencyAdd(queryGoodsSkuRateDto.getSkuAttrJson(), queryGoodsSkuRateDto.getVipsPrice().intValue())).setScale(2, BigDecimal.ROUND_HALF_UP));
                        } else {
                            queryGoodsSkuRateDto.setRealPrice(queryGoodsSkuRateDto.getWholeSalePrice().add(queryGoodsSkuRateDto.getWholeSalePrice().multiply(queryGoodsSkuRateDto.getVipsPrice().divide(new BigDecimal(1000)))).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                    }
                    queryGoodsSkuRateDto.setDiscountMoney(queryGoodsSkuRateDto.getPrice().subtract(queryGoodsSkuRateDto.getRealPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
                    //奖金折扣
                    if (commissionUserService.isClazzSupply(SystemContext.getCompanyID(), restTemplate) && isActiveAdmin(userIDGoodsByDto.getUserID())) {
                        queryGoodsSkuRateDto.setCommissionRate(commissionUserService.getcommissionRate(userIDGoodsByDto.getUserID(), queryGoodsSkuRateDto.getSkuID()));
                    }

                    //queryGoodsSkuRateDto.setPrice(null);
                    queryGoodsSkuRateDto.setVipmPrice(null);
                    queryGoodsSkuRateDto.setViphPrice(null);
                    queryGoodsSkuRateDto.setVipsPrice(null);
                }
                return list;
            }


            if (js.containsKey("isAdmin") && js.getInt("isAdmin") == 2) {
                for (QueryGoodsSkuRateDto queryGoodsSkuRateDto : list) {
                    queryGoodsSkuRateDto.setCommissionRate(null);
                    queryGoodsSkuRateDto.setDiscountRate(null);
                    queryGoodsSkuRateDto.setVipmPrice(null);
                    queryGoodsSkuRateDto.setViphPrice(null);
                }
            }

            return list;
        }
    }

    public boolean isActiveAdmin(Long userID) {
        DataResult userResult = HttpUtil.httpGet(ProConstants.getUserByID + userID, restTemplate);
        Map<String, Object> userinfo = (Map<String, Object>) userResult.getData();
        if (!Objects.equal(MapUtils.getInteger(userinfo, "state"), 2)) {//调度已经生效
            if (MapUtils.getLong(userinfo, "lastTransferTime") != null && DateUtils.isSameDay(new Date(MapUtils.getLong(userinfo, "lastTransferTime")), new Date(System.currentTimeMillis()))) {
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    private List<QueryGoodsSkuRateDto> selectGoodsSkuRate(List<Long> skuIDS) {
        List<QueryGoodsSkuRateDto> list = Lists.newArrayList();
        for (Long skuID : skuIDS) {
            list.add(goodsSkuMapper.selectGoodsSkuRate2(skuID));
        }
        return list;
    }

    private List<QueryGoodsSkuRateDto> selectGoodsSkuRateBySkus(List<Long> skuIDS) {
        List<QueryGoodsSkuRateDto> list = Lists.newArrayList();
        for (Long skuID : skuIDS) {
            list.add(goodsSkuMapper.selectGoodsSkuRateBySkus(skuID, SystemContext.getCompanyID()));
        }
        return list;
    }

    private List<QueryGoodsSkuRateDto> selectGoodsSkuRateBySkus2(List<Long> skuIDS, Long shopID) {
        List<QueryGoodsSkuRateDto> list = Lists.newArrayList();
        for (Long skuID : skuIDS) {
            list.add(goodsSkuMapper.selectGoodsSkuRateBySkus2(skuID, shopID));
        }
        return list;
    }


    public Object goodsSkuUserDiscountRate(Long userID, Long skuID) {
        DataResult dataResult = HttpUtil.httpGet(ProConstants.getUserByID + "userType/" + userID, restTemplate);
        if (dataResult.getIsSuccess() == 0) {
            logger.info("调用base服务查询adminID失败");
            return null;
        }
        JSONObject js = JSONObject.fromObject(dataResult.getData());
        Boolean a = js.containsKey("isAdmin") && js.getInt("isAdmin") == 1;
        if (js != null && ((js.containsKey("type") && js.getInt("type") == 1) || a)) {
            //1总行 2分行 3二级分行 4支行
            Integer level = js.getInt("level");
            List<Long> skuIDS = new ArrayList();
            skuIDS.add(skuID);
            //List<QueryGoodsSkuRateDto> list = goodsSkuMapper.selectGoodsSkuRate(skuIDS);
            List<QueryGoodsSkuRateDto> list = selectGoodsSkuRate(skuIDS);
            QueryGoodsSkuRateDto queryGoodsSkuRateDto = list.get(0);
            if (!Strings.isNullOrEmpty(queryGoodsSkuRateDto.getDiscountRate())) {
                JSONObject rate = JSONObject.fromObject(queryGoodsSkuRateDto.getDiscountRate());
                if (level == 2) {
                    queryGoodsSkuRateDto.setDiscountRate(rate.getString("oneLevel"));
                } else if (level == 3) {
                    queryGoodsSkuRateDto.setDiscountRate(rate.getString("twoLevel"));
                } else if (level == 4) {
                    queryGoodsSkuRateDto.setDiscountRate(rate.getString("threeLevel"));
                }
            } else {
                queryGoodsSkuRateDto.setDiscountRate(null);
            }
            return queryGoodsSkuRateDto;
        }

        return null;
    }

    /**
     * 获取中银金行开关折扣开关
     *
     * @param
     * @return
     */
    public Boolean getIsBocgold() {
        return "1".equalsIgnoreCase(bocgold);
    }


    public Integer indexCompanyID() {
        //查询所有的在售中商品
        QueryGoodsDto queryGoodsDto = new QueryGoodsDto();
        queryGoodsDto.setIsAudit(1);
        List<QueryResultGoodsDto> dataList = goodsInfoMapper.selectCondition(queryGoodsDto);
        for (QueryResultGoodsDto goodsDto : dataList) {

            JSONObject data = new JSONObject();
            data.put("goodsID", goodsDto.getGoodsID() + "");
            data.put("companyID", goodsDto.getCompanyID() + "");
            logger.info("更新索引,id:" + goodsDto.getGoodsID());
            DataResult result = HttpUtil.httpPost(ProConstants.ESURL + "/goods/index/", data, restTemplate);
            if (result.getIsSuccess() != 1) {
                logger.error("更新索引失败,id:" + goodsDto.getGoodsID());
            }

        }
        return dataList.size();
    }

    public Object delAllGoods(Long companyID) {
        List<Long> goodIds = goodsInfoMapper.selectGoodIds(companyID);
        for (Long goodID : goodIds) {
            goodsIndexService.deleteIndexing(goodID);
        }
        return "ok";
    }

    public Object delGoodsByGoodsID(Long goodsID) {
        GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(goodsID);
        if (null == goodsInfo) {
            logger.error("找不到该商品,goodsID:" + goodsID);
        }
        goodsSkuMapper.deleteByGoodsID(goodsID);
        goodsAttrStoneMapper.deleteByGoodsID(goodsID);
        goodsImagesMapper.deleteByGoodsID(goodsID);
        goodsInfoMapper.deleteByPrimaryKey(goodsID);
        goodsTagMapper.deleteGoodsTag(goodsID);
        //goodsIndexService.deleteIndexing(goodsID);
        return "ok";
    }

    public Object delBatchGoodsByGoodsID(List<Long> goodsIDs) {
        for (Long goodsID : goodsIDs) {
            delGoodsByGoodsID(goodsID);
        }
        return "success";
    }

    //云管控按品类查子类
    private String classifySearchByIdUrl;


    private String classifyUrl;

    //根据分类查询属性
    private String classifyAttrUrl;

    private String bocgold;

    private String classifyByID;

    public String getClassifyByID() {
        return classifyByID;
    }

    public void setClassifyByID(String classifyByID) {
        this.classifyByID = classifyByID;
    }

    public String getBocgold() {
        return bocgold;
    }

    public void setBocgold(String bocgold) {
        this.bocgold = bocgold;
    }

    public void setClassifyUrl(String classifyUrl) {
        this.classifyUrl = classifyUrl;
    }

    public void setClassifySearchByIdUrl(String classifySearchByIdUrl) {
        this.classifySearchByIdUrl = classifySearchByIdUrl;
    }

    public void setClassifyAttrUrl(String classifyAttrUrl) {
        this.classifyAttrUrl = classifyAttrUrl;
    }

    public Map<String, Map<String, String>> selectByGoodsIDs(List<Long> goodsIDs) {
        Map<String, Map<String, String>> map = new HashMap<>();
        List<Map<String, String>> goodsinfoList = goodsInfoMapper.selectByGoodsIDs(goodsIDs, SystemContext.getCompanyID());
        for (Map<String, String> goods : goodsinfoList) {
            map.put(goods.get("goodsID"), goods);
        }
        return map;
    }

    public Map<String, Map<String, String>> selectByGoodsIDsShop(List<Long> goodsIDs, Long shopID) {
        Map<String, Map<String, String>> map = new HashMap<>();
        List<Map<String, String>> goodsinfoList = goodsInfoMapper.selectByGoodsIDsShop(goodsIDs, SystemContext.getCompanyID(), shopID);
        for (Map<String, String> goods : goodsinfoList) {
            map.put(goods.get("goodsID"), goods);
        }
        return map;
    }

    /**
     * 批量操作商品状态
     * added by  pengzh 2018-3-20
     *
     * @param goodsIDs
     * @param state
     * @return
     */
    @Transactional
    public Object operateGoodsStateBatch(List<Long> goodsIDs, GoodsStateEnum state, Long shopID) {

        for (Long goodsID : goodsIDs) {
            GoodsStateInfoDto gsInfo = new GoodsStateInfoDto(goodsID);
            switch (state) {
                case Unapprove:
                    gsInfo.setIsAudit(2);
                    break;
                case Unshelve:
                    //gsInfo.setOnsale(0);
                    //gsInfo.setIsAudit(0);
                    //通知购物车中该商品失效
                    this.notifyGoodsCartExpireByShop(goodsID, shopID, 0);
                    notifyShopGoodsExpire(goodsID, shopID);
                    break;
                case Shelve:
                    gsInfo.setOnsale(1);
                    gsInfo.setIsAudit(0);
                    break;
                case Detele:
                    gsInfo.setIsStop(1);
                    gsInfo.setOnsale(0);
                    gsInfo.setIsAudit(0);
                    //通知购物车中该商品失效
                    this.notifyGoodsCartExpire(goodsID, 0);
                    notifyShopGoodsExpire(goodsID, shopID);
                    break;
                default:
                    throw CommonTools.createException(ErrorCodeEnum.goodsParmsError);
            }
            //操作索引
            if (state.getValue() == 2) {//商城下架商品
                logger.info("=====下架======");
                continue;
                // return 1;
            }
            int result = goodsInfoMapper.updateGoodsState(gsInfo);
            if (result == 1) {
                //  goodsIndexService.operateIndexing(state, goodsID);
            }
        }
        return 1;
    }


    /**
     * 操作店铺商品失效
     * added by  pengzh 2018-3-20
     *
     * @param goodsIDs
     * @return
     */
    private int notifyShopGoodsExpire(Long goodsIDs, Long shopID) {

//        Map<String, Object> para = new HashMap<String, Object>();
//        para.put("goodsID", goodsIDs);
//        //通知购物车中该商品下架
//        goodsInfoMapper.updateCartShopGoodsDown(para);
//        goodsInfoMapper.updateShopGoodsDown(para);
        String url = "";
        if (shopID!=null){
            url = ProConstants.deleteSubjectGoods + shopID+"/"+goodsIDs;
        }else{
            url = ProConstants.deleteSubjectGoods + SystemContext.getCompanyID()+"/"+goodsIDs;
        }

        DataResult result = HttpUtil.httpGet(url, restTemplate);

        if (!Objects.equal(result.getIsSuccess(), 1)) {
            throw new ServiceException("调用base服务失败");
        }

        goodsInfoMapper.deleteShopByGoodsID(goodsIDs, shopID);
        goodsInfoMapper.deleteShopSkuByGoodsID(goodsIDs, shopID);

        return 1;
    }


    /**
     * 查询shop商品详情v2
     *
     * @param goodsID
     * @return
     */
    public GoodsDetailsVo queryShopGoodsDetail(Long goodsID, Long shopID) {

        GoodsDetailsVo detail = new GoodsDetailsVo();
        // 获取商品信息和label信息
        GoodsInfo temp = goodsInfoMapper.selectShopByPrimaryKey(goodsID, shopID);
        if (temp == null) {
            throw CommonTools.createException(ErrorCodeEnum.goodsNoExist);
        }

        detail.setGoodsInfoVo(new GoodsInfoVo());
        BeanUtils.copyProperties(temp, detail.getGoodsInfoVo());

        // 获取图片信息
        List<GoodsImages> goodsImages = goodsImagesMapper.selectByGoodsID(goodsID);
        List<String> goodsUrls = new ArrayList<String>();
        for (GoodsImages goodsImage : goodsImages) {
            goodsUrls.add(goodsImage.getUrl());
        }
        detail.setImageUrlList(goodsUrls);
        List<GoodsSku> goodsSkuList = goodsSkuMapper.selectShopByGoodsID(goodsID, shopID);

        if (temp.getPriceType() == 1) {//实时金价
            for (GoodsSku item : goodsSkuList) {
                GoodsSkuShop skuShop = goodsSkuShopMapper.selectBySkuIDAndShopID(item.getSkuID(), shopID);
                item.setPrice(getTodayGoldPriceByOtherFee(temp.getSupplierID(), temp.getAttr(), item.getAttrJson(), skuShop.getOtherFee()));
            }
        }
        detail.setGoodsSkuList(goodsSkuList);
        //获取供应商信息
        //detail.setSupperlierInfo(remoteGetSupplierInfo(temp.getSupplierID()));
        return detail;

    }


    public GoodsDetailsVo queryShopGoodsDetailV2(Long goodsID, Long shopID, Integer type) {

        GoodsDetailsVo detail = new GoodsDetailsVo();
        // 获取商品信息和label信息
        GoodsInfo temp = new GoodsInfo();
        if (Objects.equal(type, 0)) {//未上架
            temp = goodsInfoMapper.selectByPrimaryKey(goodsID);
        } else {
            temp = goodsInfoMapper.selectShopByPrimaryKey(goodsID, shopID);
        }

        if (temp == null) {
            throw CommonTools.createException(ErrorCodeEnum.goodsNoExist);
        }

        detail.setGoodsInfoVo(new GoodsInfoVo());
        BeanUtils.copyProperties(temp, detail.getGoodsInfoVo());

        // 获取图片信息
        List<GoodsImages> goodsImages = goodsImagesMapper.selectByGoodsID(goodsID);
        List<String> goodsUrls = new ArrayList<String>();
        for (GoodsImages goodsImage : goodsImages) {
            goodsUrls.add(goodsImage.getUrl());
        }
        detail.setImageUrlList(goodsUrls);
        List<GoodsSku> goodsSkuList = new ArrayList<>();

        if (Objects.equal(type, 0)) {//未上架
            goodsSkuList = goodsSkuMapper.selectByGoodsID(goodsID);
        } else {
            goodsSkuList = goodsSkuMapper.selectShopByGoodsID(goodsID, shopID);
        }




        if (temp.getPriceType() == 1) {//实时金价
            for (GoodsSku item : goodsSkuList) {
                BigDecimal fjFee = BigDecimal.ZERO;
                if (Objects.equal(type, 0)) {
                    fjFee = item.getPrice();//未上架取建议附加费
                } else {
                    GoodsSkuShop skuShop = goodsSkuShopMapper.selectBySkuIDAndShopID(item.getSkuID(), shopID);
                    fjFee = skuShop.getOtherFee();
                }
                item.setPrice(getTodayGoldPriceByOtherFee(temp.getSupplierID(), temp.getAttr(), item.getAttrJson(), fjFee));//销售价或者零售价
            }
        }
        setAgencyPrice(goodsSkuList, temp);//设置代理价

        detail.setGoodsSkuList(goodsSkuList);
        //获取供应商信息
        //detail.setSupperlierInfo(remoteGetSupplierInfo(temp.getSupplierID()));
        return detail;

    }

    private void setAgencyPrice(List<GoodsSku> skuList, GoodsInfo goodsInfo) {
        List<GoodsClassifyRebate> distRebateList = rebateService.selectListBySellID(SystemContext.getCompanyID(), 1);
        if (distRebateList == null || distRebateList.isEmpty()) {
            throw new ServiceException("分销系数资料未设置");
        }
        Map<String, Object> rebateMap = new HashMap<String, Object>();
        for (GoodsClassifyRebate goodsClassifyRebate : distRebateList) {
            rebateMap.put(goodsClassifyRebate.getClazzID(), goodsClassifyRebate);
        }
        GoodsClassifyRebate rebate = (GoodsClassifyRebate) rebateMap.get(goodsInfo.getSubClassifyID());

        if (goodsInfo.getPriceType() == 1) {//实时金价供货价
            for (GoodsSku item : skuList) {
                item.setWholeSalePrice(getTodayGoldPrice(goodsInfo.getSupplierID(), goodsInfo.getAttr(), item.getAttrJson()));//实时金价的供货价
                item.setWholeSalePrice(item.getWholeSalePrice().add(getAgencyAdd(item.getAttrJson(), rebate.getBankVal())));
                item.setAttrJson(setNewAgencyWage(rebate.getBankVal(), item.getAttrJson(), goodsInfo.getAttr())); //修改工费
            }
        }else{
            for (GoodsSku item : skuList) {
                item.setWholeSalePrice(item.getWholeSalePrice().add(item.getWholeSalePrice().multiply(BigDecimal.valueOf(rebate.getBankVal())).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP)));
            }
        }

    }


    /**
     * 查询店铺商品-价格 集合
     *
     * @param goodsIDs
     * @return
     */
    public Object queryMultipleGoodsPriceShop(List<Long> goodsIDs, Long shopID) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (goodsIDs.size() == 0) {
            return resultMap;
        }
        List<Map<String, Object>> results = goodsInfoMapper.selectMultipleGoodsPriceShop(goodsIDs, shopID);
        for (Map<String, Object> map : results) {
            resultMap.put(map.get("goodsID").toString(), map.get("price"));
        }
        return resultMap;
    }


    /**
     * 操作商品 新增or编辑
     *
     * @param goodsDetailsVo
     * @return
     */
    @Transactional
    public Long importGoods(GoodsDetailsVo goodsDetailsVo, GoodsStoneDto stoneDto, GoodsSku goodsSku) {
        try {

            logger.info(" vo " + goodsDetailsVo.toString());

            GoodsInfoWithBLOBs gi = new GoodsInfoWithBLOBs();
            Long time = CommonUtils.getCurTimestamp();
            BeanUtils.copyProperties(goodsDetailsVo.getGoodsInfoVo(), gi);

            gi.setGoodsID(IdGen.get().nextId());
            gi.setAddTime(time);
            gi.setAddUser(goodsDetailsVo.getGoodsInfoVo().getOpreateUser());
            gi.setOnsale(1);//上架
            gi.setIsAudit(1);//未审核
            gi.setUpdateTime(time);

            // 1.保存图片到图片表
            batchInsertGoodsImages(gi, goodsDetailsVo.getImageUrlList());

            // 2.保存规格(sku)到sku表
            batchInsertGoodsSkuInfo(gi, goodsDetailsVo.getGoodsSkuList(), goodsDetailsVo.getOperateType());

            //3.插入主表信息
            //operateGoodsInfo(gi, goodsDetailsVo.getOperateType());
            gi.setCompanyID(SystemContext.getCompanyID());//赋值公司ID
            goodsInfoMapper.insertSelective(gi);

            addStoneIndexing(gi, stoneDto, goodsSku);

            return gi.getGoodsID();
        } catch (ServiceException se) {
            throw se;
        } catch (Exception e) {
            logger.info(e.getMessage());
            throw CommonTools.createException(ErrorCodeEnum.operateOtherExceptionFailure);
        }
    }


    /**
     * 创建索引
     *
     * @return
     */
    public boolean addStoneIndexing(GoodsInfoWithBLOBs goodsInfo, GoodsStoneDto stoneDto, GoodsSku goodsSku) {
        try {
            GoodsStoneDto index = new GoodsStoneDto();

            index.setGoodsID(goodsInfo.getGoodsID().toString());
            index.setGoodsName(goodsInfo.getName());
            index.setGoodsUrl(goodsInfo.getImg());
            index.setPrice(goodsInfo.getPrice().toString());
            JSONObject object = JSONObject.fromObject(goodsSku.getAttrJson());
            //index.setSku(object.containsKey("name") ? object.getString("name") : null);
            //index.setSalas(goodsInfo.getSales());
            index.setClassifyName(goodsInfo.getClassifyName());
            index.setSubClassifyName(goodsInfo.getSubClassifyName());
            index.setSupplierName(goodsInfo.getSupplierName());
            index.setAddTime(goodsInfo.getAddTime());
            index.setLabel(goodsInfo.getLabelID().toString());
            index.setCompanyID(goodsInfo.getCompanyID() + "");
            index.setPriceType(goodsInfo.getPriceType());

            index.setHxNeatness(stoneDto.getHxNeatness());
            index.setHxColor(stoneDto.getHxColor());
            index.setHxWeight(stoneDto.getHxWeight());
            index.setHxSize(stoneDto.getHxSize());
            index.setHxShape(stoneDto.getHxShape());
            index.setHxCut(stoneDto.getHxCut());

            DataResult result = HttpUtil.httpPost(ProConstants.ESURL + "/stonegoods/newIndex", index, restTemplate);
            if (result.getIsSuccess() == 0) {
                throw new ServiceException(result.getErrorDesc(), result.getErrorCode());
            }
        } catch (ServiceException se) {
            throw se;
        } catch (Exception e) {
            logger.info(e.getMessage());
            throw CommonTools.createException(ErrorCodeEnum.operateGoodsIndexingFailure);
        }
        return true;
    }

    public Object getHighQueryAttrList(ClazzObjDto list) {

        String classifyType = CommonTools.getExtString(restTemplate, "classifyType");
        list.setPlatform(Integer.parseInt(classifyType));
        DataResult result = rest.postForObject(classifyAttrUrl, list, DataResult.class);
        if (result.getIsSuccess() != 1) {
            throw new ServiceException("调用云管控服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        JSONObject json = JSONObject.fromObject(result.getData());
        logger.info("json==" + json.toString());
        List<JSONObject> queryAttr = new ArrayList<>();
        if (json.containsKey("standardAttrList") && CommonUtils.isNotEmpty(json.get("standardAttrList") + "")) {
            List<JSONObject> standardAttrList = (List<JSONObject>) json.get("standardAttrList");
            for (JSONObject attr : standardAttrList) {
                String gd_clazzAttrIsSellerShow = DataUtils.getStr(attr, "gd_clazzAttrIsSellerShow", "");
                if (attr.containsKey("clazzAttrCode") && attr.get("clazzAttrCode").toString().contains("GG")) {
                    attr.put("clazzAttrCode", attr.get("clazzAttrCode").toString().replaceAll("GG", "gg"));
                }
                if (CommonUtils.isNotEmpty(gd_clazzAttrIsSellerShow) && gd_clazzAttrIsSellerShow.equals("1")) {
                    queryAttr.add(attr);
                }
            }
        }

        if (json.containsKey("goodsAttrList") && CommonUtils.isNotEmpty(json.get("goodsAttrList") + "")) {
            List<JSONObject> standardAttrList = (List<JSONObject>) json.get("goodsAttrList");
            for (JSONObject attr : standardAttrList) {
                String gd_clazzAttrIsSellerShow = DataUtils.getStr(attr, "gd_clazzAttrIsSellerShow", "");
                if (attr.containsKey("clazzAttrCode") && attr.get("clazzAttrCode").toString().contains("GG")) {
                    attr.put("clazzAttrCode", attr.get("clazzAttrCode").toString().replaceAll("GG", "gg"));
                }
                if (CommonUtils.isNotEmpty(gd_clazzAttrIsSellerShow) && gd_clazzAttrIsSellerShow.equals("1")) {
                    queryAttr.add(attr);
                }
            }
        }
        return queryAttr;

    }

    @Transactional
    public Object moveGoodsByCompany(MoveGoodsByCompanyDto moveDto) {

        QueryGoodsDto queryGoodsDto = new QueryGoodsDto();
        queryGoodsDto.setSupplierID(moveDto.getSupplierID());
        queryGoodsDto.setClassifyID(moveDto.getClassifyID());
        queryGoodsDto.setSubClassifyID(moveDto.getSubClassifyID());
        queryGoodsDto.setCompanyID(SystemContext.getCompanyID());
        List<GoodsInfoWithBLOBs> goodsInfoWithBLOBs = goodsInfoMapper.selectWithBLOBsByCon(queryGoodsDto);

        for (GoodsInfoWithBLOBs sourceGoods : goodsInfoWithBLOBs) {
            logger.info("sourceGoodsID=" + sourceGoods.getGoodsID());
            Long targetGoodsID = IdGen.get().nextId();
            List<GoodsSku> goodsSkus = goodsSkuMapper.selectByGoodsID(sourceGoods.getGoodsID());
            List<GoodsImages> goodsImages = goodsImagesMapper.selectByGoodsID(sourceGoods.getGoodsID());
            sourceGoods.setSupplierID(moveDto.getTargetSupplierID());
            sourceGoods.setSupplierName(moveDto.targetSupplierName);
            sourceGoods.setShopID(targetGoodsID);
            sourceGoods.setCompanyID(moveDto.getTargetCompanyID());
            sourceGoods.setClassifyID(moveDto.getTargetClassifyID());
            sourceGoods.setSubClassifyID(moveDto.getTargetSubClassifyID());
            for (GoodsSku goodsSku : goodsSkus) {
                goodsSku.setSkuID(IdGen.get().nextId());
                goodsSku.setGoodsID(targetGoodsID);
            }
            int skuResult = goodsSkuMapper.insertBatch(goodsSkus);
            for (GoodsImages goodsImage : goodsImages) {
                goodsImage.setImgID(IdGen.get().nextId());
                goodsImage.setGoodsID(targetGoodsID);
            }
            int imgResult = goodsImagesMapper.insertBatch(goodsImages);
            sourceGoods.setGoodsID(targetGoodsID);
            int goodsResult = goodsInfoMapper.insertSelective(sourceGoods);
            if (Objects.equal(sourceGoods.getOnsale(), 1) && Objects.equal(sourceGoods.getIsAudit(), 1)) {
                goodsIndexService.addIndexing(targetGoodsID);
            }
            logger.info("targerGoodsID=" + targetGoodsID + "goodsResult=" + goodsResult + "skuResult=" + skuResult + "imgResult=" + imgResult);
        }

        return "success";

    }

    @Transactional
    public Object deleteGoodsByCompany(Long supplierID, String classifyID, String subClassifyID, Long companyID) {
        QueryGoodsDto queryGoodsDto = new QueryGoodsDto();
        queryGoodsDto.setSupplierID(supplierID);
        queryGoodsDto.setClassifyID(classifyID);
        queryGoodsDto.setSubClassifyID(subClassifyID);
        queryGoodsDto.setCompanyID(companyID);
        List<GoodsInfoWithBLOBs> goodsInfoWithBLOBs = goodsInfoMapper.selectWithBLOBsByCon(queryGoodsDto);
        for (GoodsInfoWithBLOBs sourceGoods : goodsInfoWithBLOBs) {
            if (Objects.equal(sourceGoods.getOnsale(), 1) && Objects.equal(sourceGoods.getIsAudit(), 1)) {
                goodsIndexService.deleteIndexing(sourceGoods.getGoodsID());
            }
            goodsSkuMapper.deleteByGoodsID(sourceGoods.getGoodsID());
            goodsImagesMapper.deleteByGoodsID(sourceGoods.getGoodsID());
            goodsInfoMapper.deleteByPrimaryKey(sourceGoods.getGoodsID());

        }

        return "success";
    }

    @Transactional
    public Object attrAdjust(MoveGoodsByCompanyDto moveGoodsByCompanyDto) {
        QueryGoodsDto queryGoodsDto = new QueryGoodsDto();
        queryGoodsDto.setCompanyID(moveGoodsByCompanyDto.getTargetCompanyID());
        queryGoodsDto.setClassifyID(moveGoodsByCompanyDto.getTargetClassifyID());
        queryGoodsDto.setSubClassifyID(moveGoodsByCompanyDto.getTargetSubClassifyID());
        List<GoodsInfoWithBLOBs> goodsInfoWithBLOBs = goodsInfoMapper.selectWithBLOBsByCon(queryGoodsDto);


        for (GoodsInfoWithBLOBs sourceGoods : goodsInfoWithBLOBs) {
            List<JSONObject> jsonList = JsonUtil.toList(sourceGoods.getAttr());

            GoodsSku sku = goodsSkuMapper.selectByGoodsID(sourceGoods.getGoodsID()).get(0);
            JSONObject skuAttrs = JSONObject.fromObject(sku.getAttrJson());

            String name = skuAttrs.get("name") + "";
            JSONObject nameJson = new JSONObject();
            if (CommonUtils.isNotEmpty(name)) {
                String[] a = name.split("\\+");
                for (int i = 0; i < a.length; i++) {
                    String[] b = a[i].split(":");
                    if (Objects.equal(b.length, 2)) {
                        nameJson.put(a[i].split(":")[0], a[i].split(":")[1]);
                    }
                }
            }

            if (skuAttrs.containsKey("hxFireGrade")) {//火彩级别
                JSONObject j = new JSONObject();
                j.put("cfadid", "2_s9kakTWqQ05q56M074A");
                j.put("clazzattrcode", "hxFireGrade");
                j.put("clazzattrval", skuAttrs.get("hxFireGrade"));
                j.put("clazzattrname", "火彩分级");
                jsonList.add(j);
                skuAttrs.remove("hxFireGrade");
                skuAttrs.get("name");
                nameJson.remove("火彩分级");
            }

            if (skuAttrs.containsKey("hxSize")) {//尺寸
                JSONObject j = new JSONObject();
                j.put("cfadid", "xyfR7QDR7K_MB5SccJ2Hg");
                j.put("clazzattrcode", "hxSize");
                j.put("clazzattrval", skuAttrs.get("hxSize"));
                j.put("clazzattrname", "尺寸");
                jsonList.add(j);
                skuAttrs.remove("hxSize");
                skuAttrs.get("name");
                nameJson.remove("尺寸规格");
            }
            /*if(skuAttrs.containsKey("hxNeatness")){//净度
                JSONObject j = new JSONObject();
                j.put("cfadid","KhBBpH0RFKGUsjK3rPQaw");
                j.put("clazzattrcode","hxNeatness");
                j.put("clazzattrval",skuAttrs.get("hxNeatness"));
                j.put("clazzattrname","净度");
                jsonList.add(j);
                skuAttrs.remove("hxNeatness");
                nameJson.remove("净度");
            }
            if(skuAttrs.containsKey("hxCutGrade")){//切工分级
                JSONObject j = new JSONObject();
                j.put("cfadid","gt-96HfTF6qTF-XIUhHtA");
                j.put("clazzattrcode","hxCutGrade");
                j.put("clazzattrval",skuAttrs.get("hxCutGrade"));
                j.put("clazzattrname","切工分级");
                jsonList.add(j);
                skuAttrs.remove("hxCutGrade");
                nameJson.remove("切工级别");
            }
            if(skuAttrs.containsKey("msWeight")){//主石重
                JSONObject j = new JSONObject();
                j.put("cfadid","qYVZLuwT3aH8LgLytFqBg");
                j.put("clazzattrcode","msWeight");
                j.put("clazzattrval",skuAttrs.get("msWeight"));
                j.put("clazzattrname","主石重");
                jsonList.add(j);
                skuAttrs.remove("msWeight");
                nameJson.remove("主石重");
            }
            if(skuAttrs.containsKey("hxLucency")){//透明度
                JSONObject j = new JSONObject();
                j.put("cfadid","pFX7fKRSGOCiAEt_jAy-Q");
                j.put("clazzattrcode","hxLucency");
                j.put("clazzattrval",skuAttrs.get("hxLucency"));
                j.put("clazzattrname","透明度");
                jsonList.add(j);
                skuAttrs.remove("hxLucency");
                nameJson.remove("透明度");
            }
            if(skuAttrs.containsKey("hxShape")){ //形状
                JSONObject j = new JSONObject();
                j.put("cfadid","MNidQp5Q4Cklg_wdfM6Ag");
                j.put("clazzattrcode","hxShape");
                j.put("clazzattrval",skuAttrs.get("hxShape"));
                j.put("clazzattrname","形状");
                jsonList.add(j);
                skuAttrs.remove("hxShape");
                nameJson.remove("形状");
            }

            if(skuAttrs.containsKey("hxCutType")){ //切工类型
                JSONObject j = new JSONObject();
                j.put("cfadid","S52UgHoSISCdviUaLi9eQ");
                j.put("clazzattrcode","hxCutType");
                j.put("clazzattrval",skuAttrs.get("hxCutType"));
                j.put("clazzattrname","切工类型");
                jsonList.add(j);
                skuAttrs.remove("hxCutType");
                nameJson.remove("切工类型");
            }*/


            GoodsInfoWithBLOBs goods = new GoodsInfoWithBLOBs();
            goods.setGoodsID(sourceGoods.getGoodsID());
            goods.setAttr(jsonList.toString());
            GoodsSku goodsSKu = new GoodsSku();
            goodsSKu.setSkuID(sku.getSkuID());
            skuAttrs.put("name", getAttrNameByJson(nameJson));
            goodsSKu.setAttrJson(skuAttrs.toString());
            goodsSkuMapper.updateByPrimaryKeySelective2(goodsSKu);
            goodsInfoMapper.updateByPrimaryKeySelective(goods);

        }

        return "success";

    }

    public String getAttrNameByJson(JSONObject nameJson) {
        String newName = "";
        Iterator<String> sIterator = nameJson.keys();
        while (sIterator.hasNext()) {
            // 获得key
            String key = sIterator.next();
            // 根据key获得value, value也可以是JSONObject,JSONArray,使用对应的参数接收即可
            String value = nameJson.getString(key);
            newName += key + ":" + value + "+";
        }
        if (CommonUtils.isNotEmpty(newName)) {
            newName = newName.substring(0, newName.length() - 1);
        }
        return newName;
    }


    /**
     * 商城商品分类标签列表
     *
     * @param clazzId 分类id
     * @return
     */
    public Object getGoodsClazzTagList(String clazzId) {
        return classifyTagMapper.selectListByClazzIdShopId(clazzId, SystemContext.getCompanyID());
    }


    /**
     * 批量更新商品标签
     *
     * @param gi
     * @param tagList 商品标签list
     */
    private void batchInsertGoodsTags(GoodsInfo gi, List<Long> tagList) {
        try {
            goodsTagMapper.deleteGoodsTag(gi.getGoodsID());
            if (tagList == null || tagList.size() == 0) {
                return;
            }
            int index = 0;
            for (Long tagID : tagList) {
                goodsTagMapper.insertSelective(new GoodsTag(IdGen.get().nextId(), gi.getGoodsID(), tagID, index));
                index++;
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
            throw CommonTools.createException(ErrorCodeEnum.goodsTagError);
        }
    }
    @Transactional
    public Object   setOrigPrice(GoodsDetailsVo goodsDetailsVo) {

        GoodsInfoVo goodsInfoVo = goodsDetailsVo.getGoodsInfoVo();
        Long shopID = goodsInfoVo.getShopID();
        Long goodsID = goodsInfoVo.getGoodsID();

        GoodsClassifyRebate rebate = getRebateByGoodsID(goodsID);

        List<GoodsSku> goodsSkuListDto = goodsDetailsVo.getGoodsSkuList();
        GoodsShop goodsShop = goodsShopMapper.selectByGoodsIDAndShopID(goodsID,shopID);
        BigDecimal goodsPrice =null;
        BigDecimal goodsPriceOrig =null;
        boolean flag = true;
        List<GoodsSkuShop> flagSkuShopList = new ArrayList<>();

        for (GoodsSku goodsSkuDto:  goodsSkuListDto ) {
            GoodsSku sku = goodsSkuMapper.selectByPrimaryKey(goodsSkuDto.getSkuID());
            BigDecimal skuAgency = sku.getWholeSalePrice().add(sku.getWholeSalePrice().multiply(BigDecimal.valueOf(rebate.getBankVal())).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP));//代理价

            GoodsSkuShop skuShop = goodsSkuShopMapper.selectBySkuIDAndShopID(goodsSkuDto.getSkuID(),shopID);

            BigDecimal origPrice = skuShop.getOrigPrice()==null?skuShop.getPrice():skuShop.getOrigPrice();//原价格
            if(goodsSkuDto.getPrice().compareTo(skuAgency)==-1 || goodsSkuDto.getPrice().compareTo(origPrice)==1){
                throw  new ServiceException("促销价不得低于代理价，不得高于销售价");
            }

            skuShop.setOrigPrice(origPrice);

            skuShop.setPrice(goodsSkuDto.getPrice());//最新促销价格

            if(goodsPrice==null){
                goodsPrice=skuShop.getPrice();
                goodsPriceOrig= skuShop.getOrigPrice();
            }

            if(skuShop.getPrice().compareTo(skuShop.getOrigPrice())==0){
                flagSkuShopList.add(skuShop);
            }else{
                flag = false;
            }

            goodsSkuShopMapper.updateByPrimaryKeySelective(skuShop);
        }
        goodsShop.setPrice(goodsPrice);
        goodsShop.setOrigPrice(goodsPriceOrig);
        goodsShopMapper.updateByPrimaryKeySelective(goodsShop);
        if(flag){//表示不设置促销价，还原了
            for (GoodsSkuShop skuShop: flagSkuShopList) {
                skuShop.setOrigPrice(null);
                goodsSkuShopMapper.updateByPrimaryKey(skuShop);
            }
            goodsShop.setOrigPrice(null);
            goodsShopMapper.updateByPrimaryKey(goodsShop);
        }

        return "success";

    }

    public GoodsClassifyRebate getRebateByGoodsID(Long goodsID){
        GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(goodsID);
        List<GoodsClassifyRebate> distRebateList = rebateService.selectListBySellID(SystemContext.getCompanyID(), 1);
        if (distRebateList == null || distRebateList.isEmpty()) {
            throw new ServiceException("分销系数资料未设置");
        }
        Map<String, Object> rebateMap = new HashMap<String, Object>();
        for (GoodsClassifyRebate goodsClassifyRebate : distRebateList) {
            rebateMap.put(goodsClassifyRebate.getClazzID(), goodsClassifyRebate);
        }
        GoodsClassifyRebate rebate = (GoodsClassifyRebate) rebateMap.get(goodsInfo.getSubClassifyID());
        return rebate;

    }

/*    public BigDecimal getAgencyBySkuID(Long goodsID,Long skuID){

        GoodsSku goodsSku = goodsSkuMapper.selectByPrimaryKey(skuID);

        GoodsClassifyRebate rebate = getRebateByGoodsID(goodsID)

        return  goodsSku.getWholeSalePrice().add(goodsSku.getWholeSalePrice().multiply(BigDecimal.valueOf(rebate.getBankVal())).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP));

    }*/

    /*public static void main(String[] args) {
        String name = "切工类型:素面+切工分级:好+货重:12克+颜色:粉色+透明度:好+形状:水滴形+尺寸规格:12";
        JSONObject nameJson = new JSONObject();
        if (CommonUtils.isNotEmpty(name)){
            String[] a = name.split("\\+");
            for (int i=0;i<a.length;i++){
                nameJson.put(a[i].split(":")[0],a[i].split(":")[1]);
            }
        }
        nameJson.remove("切工类型");
        String newName = "";
        Iterator<String> sIterator = nameJson.keys();
        while(sIterator.hasNext()) {
            // 获得key
            String key = sIterator.next();
            // 根据key获得value, value也可以是JSONObject,JSONArray,使用对应的参数接收即可
            String value = nameJson.getString(key);
            newName += key+":"+value+"+";
        }
        if (CommonUtils.isNotEmpty(newName)){
            newName = newName.substring(0,newName.length()-1);
        }
        System.out.print(newName);
    }*/
}
